简体   繁体   English

代入 AWS IAM 角色

[英]AWS IAM role assuming

Trying to assume the IAM role and get temporary credentials for accessing AWS services.尝试代入 IAM 角色并获取用于访问 AWS 服务的临时凭证。 I have configured the IAM role in the AWS and tried the below code我已经在 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);

But i am getting the below exception , anyone has any idea但我得到以下例外,任何人都知道

10:38:50.377 [main] DEBUG com.amazonaws.metrics.AwsSdkMetrics - Admin mbean registered under com.amazonaws.management:type=AwsSdkMetrics Exception in thread "main" java.lang.NoSuchFieldError: SERVICE_ID at com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient.executeAssumeRole(AWSSecurityTokenServiceClient.java:479) at com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient.assumeRole(AWSSecurityTokenServiceClient.java:460) 10:38:50.377 [main] DEBUG com.amazonaws.metrics.AwsSdkMetrics - 在 com.amazonaws.management:type=AwsSdkMetrics 下注册的管理 mbean 线程“main”java.lang.NoSuchFieldError: SERVICE_ID at service.amazonaws. securitytoken.AWSSecurityTokenServiceClient.executeAssumeRole(AWSSecurityTokenServiceClient.java:479) at com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient.assumeRole(AWSSecurityTokenServiceClient.java:460)

To get temporary credentials, on the role that you want to assume, you need to set a trust relationship.要获取临时凭证,您需要在要承担的角色上设置信任关系。 In the trust relationship, specify the user to trust.在信任关系中,指定信任的用户。 For 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"
      }
    ]
  }

Now you can, for example, run a Java program (Java V2) to invoke the assumeRole operation.例如,现在您可以运行 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);
       }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 本地设置的 AWS S3 IAM 角色 - AWS S3 IAM role for Local setup 使用IAM Role从Java访问AWS S3 - access AWS S3 from java using IAM Role AWS Java SDK v2 未在 EKS 中使用 IRSA IAM 角色 - AWS Java SDK v2 not using IRSA IAM Role in EKS 如何使用与EC2实例关联的IAM角色从Amazon检索临时AWS凭证(在Java中)? - How to retrieve temporary AWS credentials from Amazon using IAM role associated with the EC2 instance(in java)? 使用 IAM 用户的访问密钥为第三方 AWS 账户代入角色失败 - Failed to assume role for third-party AWS account using IAM user's access key 如何为AWS EC2实例中部署的Spring Boot Rest API Web服务创建IAM角色 - how to create IAM role for a spring boot rest api web service deployed in aws ec2 instance 在使用分配的 IAM 进行访问的 ec2 上使用 java SDK 在 aws 中扮演不同的角色 - assume different role in aws using java SDK on ec2 which uses assigned IAM for access 如何使用 IAM 角色通过 aws sdk (java) 从 ECS 容器调用 s3 存储桶 - How to call s3 bucket from ECS container via aws sdk (java) by using IAM role 如何配置 spring 应用程序以在 aws 上使用 IAM 角色(在 AWS ECS 内运行)并在开发环境上使用凭证? - How can I configure spring app to use IAM Role(running inside AWS ECS) on aws and credentials on dev env? 如何使本地计算机承担IAM角色 - how to make local machine to assume IAM role
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM