如何生成使用临时安全凭证签名的HTTPS API请求(URL)以访问AWS S3对象。我可以使用amazon java sdk访问对象但我想生成带有临时安全凭证的完整URL,如预签名网址。 包com.siriusxm.repo.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.amazonaws.auth.BasicSessionCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient;
import com.amazonaws.services.securitytoken.model.Credentials;
import com.amazonaws.services.securitytoken.model.GetSessionTokenRequest;
import com.amazonaws.services.securitytoken.model.GetSessionTokenResult;
import com.siriusxm.repo.DownloadServiceImpl;
public class TemporaryCredential {
private static String bucketName = "myrepo";
private static String key = "test.pdf";
public static void main(String[] args) {
System.out.println("");
AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(
new ProfileCredentialsProvider());
// stsClient.setRegion(regionName);sts.us-west-2.amazonaws.com
//
// Start a session.
GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest();
GetSessionTokenResult sessionTokenResult = stsClient
.getSessionToken(getSessionTokenRequest);
Credentials sessionCredentials = sessionTokenResult.getCredentials();
System.out.println("Session Credentials: "
+ sessionCredentials.toString());
// Package the session credentials as a BasicSessionCredentials
// object for an S3 client object to use.
BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(
sessionCredentials.getAccessKeyId(),
sessionCredentials.getSecretAccessKey(),
sessionCredentials.getSessionToken());
AmazonS3Client s3object = new AmazonS3Client(basicSessionCredentials);
// Test. For example, get object keys for a given bucket.
ObjectListing objects = s3object.listObjects(bucketName);
s3object.getObject( new GetObjectRequest(bucketName, key));
System.out.println("No. of Objects = "
+ objects.getObjectSummaries().size());
}
}
此代码生成动态访问密钥,密钥和安全令牌。现在我需要使用带签名的授权头生成url,以便我可以直接访问S3对象。是否有路径?
从这段代码我想用x-amz-security-token
生成url答案 0 :(得分:4)
如果你想在java中这样做,你必须使用AmazonS3.generatePresignedUrl
AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
java.util.Date expiration = new java.util.Date();
long msec = expiration.getTime();
msec += 1000 * 60 * 60; // 1 hour.
expiration.setTime(msec);
GeneratePresignedUrlRequest generatePresignedUrlRequest =
new GeneratePresignedUrlRequest(bucketName, objectKey);
generatePresignedUrlRequest.setMethod(HttpMethod.GET); // Default.
generatePresignedUrlRequest.setExpiration(expiration);
URL s = s3client.generatePresignedUrl(generatePresignedUrlRequest);
如果您想从控制台执行此操作,请转到您的s3存储桶,单击该对象上的下载。这会显示一个框,您可以单击“下载”。如果右键单击此链接并复制地址链接,则会获得此对象的预签名URL