首页 > 解决方案 > AWS IAM 角色代入

问题描述

尝试担任 IAM 角色并获取用于访问 AWS 服务的临时凭证。我已经在 AWS 中配置了 IAM 角色并尝试了以下代码

String clientRegion = "eu-west-1";
    String roleARN = "arn:aws:iam::83883883:role/myrole";
    String roleSessionName = "rolename";


    try {
        // Creating the STS client is part of your trusted code. It has
        // the security credentials you use to obtain temporary security credentials.
        AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
                                                .withCredentials(new ProfileCredentialsProvider())
                                                .withRegion(clientRegion)
                                                .build();

        // Assume the IAM role. Note that you cannot assume the role of an AWS root account;
        // Amazon S3 will deny access. You must use credentials for an IAM user or an IAM role.
        AssumeRoleRequest roleRequest = new AssumeRoleRequest()
                                                .withRoleArn(roleARN)
                                                .withRoleSessionName(roleSessionName);
        stsClient.assumeRole(roleRequest);

        // Start a session.
        GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest();
        // The duration can be set to more than 3600 seconds only if temporary
        // credentials are requested by an IAM user rather than an account owner.
        getSessionTokenRequest.setDurationSeconds(7200);
        GetSessionTokenResult sessionTokenResult = stsClient.getSessionToken(getSessionTokenRequest);
        Credentials sessionCredentials = sessionTokenResult.getCredentials();

        // Package the temporary security credentials as a BasicSessionCredentials object 
        // for an Amazon S3 client object to use.
        BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(
                sessionCredentials.getAccessKeyId(), sessionCredentials.getSecretAccessKey(),
                sessionCredentials.getSessionToken());

        System.out.println(basicSessionCredentials);

但我得到以下例外,任何人都有任何想法

10:38:50.377 [main] 调试 com.amazonaws.metrics.AwsSdkMetrics - 在 com.amazonaws.management:type=AwsSdkMetrics 下注册的管理员 mbean 在线程“main”java.lang.NoSuchFieldError 中出现异常: com.amazonaws.services 中的SERVICE_ID 。 securitytoken.AWSSecurityTokenServiceClient.executeAssumeRole(AWSSecurityTokenServiceClient.java:479) 在 com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient.assumeRole(AWSSecurityTokenServiceClient.java:460)

标签: javaamazon-web-servicesamazon-iam

解决方案


要获取临时凭证,在您要担任的角色上,您需要设置信任关系。在信任关系中,指定要信任的用户。例如:

{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Principal": {
          "AWS": "<Specify the ARN of your IAM user you are using in this code example>"
        },
        "Action": "sts:AssumeRole"
      }
    ]
  }

例如,现在您可以运行 Java 程序 (Java V2) 来调用假设角色操作。

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
import software.amazon.awssdk.services.sts.model.StsException;
import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
import software.amazon.awssdk.services.sts.model.Credentials;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;

/**
 * To make this code example work, create a Role that you want to assume.
 * Then define a Trust Relationship in the AWS Console. YOu can use this as an example:
 *
 * {
 *   "Version": "2012-10-17",
 *   "Statement": [
 *     {
 *       "Effect": "Allow",
 *       "Principal": {
 *         "AWS": "<Specify the ARN of your IAM user you are using in this code example>"
 *       },
 *       "Action": "sts:AssumeRole"
 *     }
 *   ]
 * }
 *
 *  For more information, see "Editing the Trust Relationship for an Existing Role" in the AWS Directory Service guide.
 */

public class AssumeRole {

    public static void main(String[] args) {

         String roleArn = "arn:aws:iam::814548047983:role/s3role" ; // args[0];
        String roleSessionName = "mysession101"; // args[1];

        Region region = Region.US_EAST_1;
        StsClient stsClient = StsClient.builder()
                .region(region)
                .build();

       try {
        AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
                .roleArn(roleArn)
                .roleSessionName(roleSessionName)
                .build();

           AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);

           Credentials myCreds = roleResponse.credentials();

           //Display the time when the temp creds expire
           Instant exTime = myCreds.expiration();

           // Convert the Instant to readable date
           DateTimeFormatter formatter =
                   DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
                           .withLocale( Locale.US)
                           .withZone( ZoneId.systemDefault() );

           formatter.format( exTime );
           System.out.println("The temporary credentials expire on " + exTime );

       } catch (StsException e) {
           System.err.println(e.getMessage());
           System.exit(1);
       }
   }
}

推荐阅读