将文件上传到s3

时间:2016-04-05 06:53:49

标签: java amazon-web-services amazon-cognito

public static void main(String[] args) {
    AmazonCognitoIdentity identityClient = new AmazonCognitoIdentityClient(new AnonymousAWSCredentials());
    identityClient.setEndpoint("cognito-identity.us-east-1.amazonaws.com");
    identityClient.setRegion(Region.getRegion(Regions.US_EAST_1));
    GetIdRequest idRequest = new GetIdRequest();
    idRequest.setAccountId("XXXXXXXXX");
    idRequest.setIdentityPoolId("XXXXXXX");
    GetIdResult idResp = identityClient.getId(idRequest);
    String identityId = idResp.getIdentityId();
    GetOpenIdTokenRequest tokenRequest = new GetOpenIdTokenRequest();
    tokenRequest.setIdentityId(identityId);
    GetOpenIdTokenResult tokenResp = identityClient.getOpenIdToken(tokenRequest);
    String openIdToken = tokenResp.getToken();
    AWSSecurityTokenService stsClient = new AWSSecurityTokenServiceClient(new AnonymousAWSCredentials());
    AssumeRoleWithWebIdentityRequest stsReq = new AssumeRoleWithWebIdentityRequest();
    stsReq.setRoleArn(
            "arn:aws:cognito-identity:us-east-1:XXXXXX:identitypool/us-east-1:XXXXXXX");
    stsReq.setWebIdentityToken(openIdToken);
    stsReq.setRoleSessionName("AppTestSession");


    AssumeRoleWithWebIdentityResult stsResp = stsClient.assumeRoleWithWebIdentity(stsReq);
    Credentials stsCredentials = stsResp.getCredentials();

    AWSSessionCredentials sessionCredentials = new BasicSessionCredentials(stsCredentials.getAccessKeyId(),
            stsCredentials.getSecretAccessKey(), stsCredentials.getSessionToken());
    Date sessionCredentialsExpiration = stsCredentials.getExpiration();
    System.out.println("session credentials expiration -> " + sessionCredentialsExpiration);

    String bucketName = "s3fileupload";
    String keyName = "cognitokey";
    String uploadFileName = "/home/fresher/Downloads/say-hello.jpg";
    AmazonS3 s3client = new AmazonS3Client(sessionCredentials);
    s3client.setEndpoint("s3fileupload.s3-website-us-west-2.amazonaws.com");

    File file = new File(uploadFileName);
    s3client.putObject(new PutObjectRequest(bucketName, keyName, file));
}

我收到一条说“请求ARN无效”的异常。 你能指导我一下吗?

请求ARN无效(服务:AWSSecurityTokenService;状态代码:400;错误代码:ValidationError;请求ID:XXXXXXXXXXXXXXXXXX)

1 个答案:

答案 0 :(得分:0)

在您的STS请求中,您传递的是Cognito Identity的ARN,而不是您想要获取凭据的角色Arn。

此处的值应为您在IAM中配置的角色的ARN。它看起来像这样:

ARN:AWS:IAM :: 123456789012:角色/ ROLE_NAME