I'm trying to generate a temporary credentials access key and secret key. I've used AssumeRole
. The description says it generates an access key and secret key. But GetSessionTokenResult
can also generate an access key and secret key. Then what's the use of assumeRole?
AWSSecurityTokenService awsSecurityTokenService =
AWSSecurityTokenServiceClientBuilder
.standard().withCredentials(new ProfileCredentialsProvider())
.withRegion(region).build();
AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
.withRoleArn(
"arn:aws:iam::account-id:role/p-27c229ade194_ec2")
.withRoleSessionName("RedshiftSession");
AssumeRoleResult assumeRoleResult = awsSecurityTokenService
.assumeRole(assumeRoleRequest);
GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest();
getSessionTokenRequest.setDurationSeconds(1200);
GetSessionTokenResult getSessionTokenResult = awsSecurityTokenService
.getSessionToken(getSessionTokenRequest);
Credentials sessionCredentials = getSessionTokenResult.getCredentials();
final String adminAccessKeyId = sessionCredentials.getAccessKeyId();
final String adminAccessSecretKey = sessionCredentials
.getSecretAccessKey();
Earlier using assumeRole it showed error => aws:iam::user/admin is not sts:assumeRole on resource role aws:iam::role/role_id
.
By adding aws:iam::user/admin
in trusted relationship of role_id
it worked.
If I will comment out AccessRole
and its other called class. I can generate an access key and secret key. What's the purpose of using AssumeRole
?
There are several methods to obtain temporary credentials, depending upon your requirements:
Also, AssumeRole can be used to gain cross-account access. For example, a user in Account A could assume a role in Account B, which grants access to resources in Account B. This is not possible via GetSessionToken.
I always find this article useful to explain the differences: Understanding the API Options for Securely Delegating Access to Your AWS Account | AWS Security Blog
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With