Steps to implement sts code.

发布时间 2023-11-28 00:25:54作者: 灰色人生qwer
Steps to implement sts code.
1. create IAM user - IAM
2. give few permission to this IAM user - p1, p2
3. create one role which IAM user can assume it - R1
4. create one policy which will allow IAM user to assume R1(role ARN) role - p3
5. call Assume role api to finally assume the role R1 - Java
aws iam create-user --user-name Tyler

{
  "User": {
    "Path": "/",
    "UserName": "Tyler",
    "UserId": "AIDAWSIFEYCAWKUI6026W",
    "Arn": "451519234177:user/Tyler",
    "CreateDate": "2021-03-28T08:13:12+00:00"
  }
}
aws iam create-access-key --user-name Tyler

{
  "AccessKey": {
    "UserName": "Tyler",
    "AccessKeyId":"AKIAWSIFEYCASZBVUIUYD",
    "Status": "Active",
    "SecretAccessKey": "3pFfJieG/n7u76+FrCPnX5nQRW2H4cxm3Td3e10s",
    "CreateDate": "2021-03-28T-08:13:34+00:00"
  }
}

aws configure

Create policy to allow list lambda function and test in aws-cli.
{
  "Version": "2012-10-17",
  "Satement": [
    {
      "Effect": "Allow",
      "Action": [
        "lambda:ListFunctions"
      ],
      "Resource": "*"
    }
  ]
}

aws lambda list-functions --region us-west-1

Edit policy to also allow assume 'AssumeThisRole' role.

{
  "Version": "2012-10-17",
  "Satement": [
    {
      "Effect": "Allow",
      "Action": [
        "lambda:ListFunctions"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "sts:AssumeRole"
      ],
      "Resource": "arn:aws:iam::451519234177:role/AssumeThisRole"
    }
  ]
}

Create IAM role which is AssumeThisRole.

Create Policy to allow list roles to AssumeThisRole.

{
  "Version": "2012-10-17",
  "Satement": [
    {
      "Effect": "Allow",
      "Action": [
        "iam:ListRoles"
      ],
      "Resource": "*"
    }
  ]
}

Edit Trust Relationship to allow who can assume this role (AssumeThisRole).

{
  "Version": "2012-10-17",
  "Satement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::451519234177:user/Tyler"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

Using Java sdk to test sts.

Add dependency to pom.xml.

<!--To assume role-->
<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-sts</artifactId>
</dependency>
<!--To list role -->
<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-iam</artifactId>
</dependency>

Wirte Java code to call assumeRole API.

package com.tyler.config.test.aws.sts;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicSessionCredentials;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder;
import com.amazonaws.services.identitymanagement.model.DeleteRoleRequest;
import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder;
import com.amazonaws.services.securitytoken.model.AssumeRoleRequest;
import com.amazonaws.services.securitytoken.model.AssumeRoleResult;
import com.amazonaws.services.securitytoken.model.Credentials;

public class StsTest {
    public static void main(String[] args) {
        String roleARN = "arn:aws::451519234177:role/AssumeThisRole"; // The role arn which we want to assume.
        String roleSessionName = "Session_1"; // Any name we can write.

        AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard().build();
        /**
         * withRoleArn: The role arn which we want to assume.
         * withRoleSessionName: The roleSessionName you writed.
         * withDurationSeconds: To set how long could be accessable by this role.
         */
        AssumeRoleRequest roleRequest = new AssumeRoleRequest().withRoleArn(roleARN).withRoleSessionName(roleSessionName).withDurationSeconds(3600);
        AssumeRoleResult assumeResult = stsClient.assumeRole(roleRequest);
        // Call assumeRole API
        Credentials temporaryCredentials = assumeResult.getCredentials();

        System.out.println("ACCESS_KEY_ID ===> " + temporaryCredentials.getAccessKeyId());
        System.out.println("SECRET_ACCESS_KEY ===> " + temporaryCredentials.getSecretAccessKey());
        System.out.println("SESSION_TOKEN ===> " + temporaryCredentials.getSessionToken());

        BasicSessionCredentials credentials = new BasicSessionCredentials(temporaryCredentials.getAccessKeyId(), temporaryCredentials.getSecretAccessKey(), temporaryCredentials.getSessionToken());
        AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
        AmazonIdentityManagement client = AmazonIdentityManagementClientBuilder.standard().withCredentials(credentialsProvider).build();

        System.out.println();
        System.out.println("************************LIST-ROLES************************");
        client.listRoles().getRoles().forEach(r -> System.out.println(r.getArn()));

        client.deleteRole(new DeleteRoleRequest().withRoleName("amplify-amplifygraphqldema-dev-183938-authRole")); // try to delete a role - it will make exception because we only give the ListRoles permission in the policy

    }
}