I will follow the official page of aws. https://docs.aws.amazon.com/ja_jp/AmazonS3/latest/dev/RESTAuthentication.html
In the authentication header
Authorization: AWS AWSAccessKeyId:Signature
However, it is quite troublesome to make this Signature.
I happened to use it in a Java project, so I'll post it instead of a memo.
This time, https://[BUCKET].[ENDPOINT]/[FILE_NAME] I am accessing with a certificate.
protected void getFile() throws NoSuchAlgorithmException, InvalidKeyException, ClientProtocolException, IOException {
String resource= "/" + BUCKET + "/" +FILE_NAME;
String contentType = "application/octet-stream";
String md5 = "";
String daHeader = "x-amz-meta-user:" + USER_ID;
//
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
df.setTimeZone(c.getTimeZone());
//Creating a StringToSign
String now = df.format(c.getTime());
String stringToSign="GET" + "\n" + md5 + "\n" + contentType + "\n" + now + "\n" + daHeader + "\n" + resource;
//Creating a signature
SecretKeySpec sk = new SecretKeySpec(S3_SECRET.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(sk);
byte[] dataBytes = stringToSign.getBytes("UTF-8");
byte[] signatureBytes = mac.doFinal(dataBytes);
String signature = new String(Base64.encodeBase64(signatureBytes), "UTF-8");
//Get request
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://" + BUCKET + '.' + END_POINT + "/" + FILE_NAME);
request.setHeader("Host", BUCKET + '.' + END_POINT);
request.setHeader("Date", now.toString());
request.setHeader("Content-Type", contentType);
request.setHeader("Authorization", "AWS" + " " + S3_KEY + ':' + signature);
request.setHeader("x-amz-meta-user", USER_ID);
HttpResponse response = client.execute(request);
}
Recommended Posts