Issue
I am currently facing an issue while attempting to retrieve temporary credentials using an IAM Role for an EC2 instance in my AWS environment. I'm using the AWS SDK for .NET, here is the error log
An unhandled exception has occurred while executing the request. Amazon.SecurityToken.AmazonSecurityTokenServiceException: Cannot call GetSessionToken with session credentials 2023-10-06T13:37:15.567408512Z ---> Amazon.Runtime.Internal.HttpErrorResponseException: Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown. 2023-10-06T13:37:15.567411486Z at Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken) 2023-10-06T13:37:15.567413696Z at Amazon.Runtime.Internal.HttpHandler`1.InvokeAsync[T](IExecutionContext executionContext) 2023-10-06T13:37:15.567415774Z at Amazon.Runtime.Internal.Unmarshaller.InvokeAsync[T](IExecutionContext executionContext) 2023-10-06T13:37:15.567417810Z at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext)
here is the code snippet I'm using to try and obtain these credentials:
using var stsClient = new AmazonSecurityTokenServiceClient(region);
var getSessionTokenRequest = new GetSessionTokenRequest
{
DurationSeconds = 3600 // seconds
};
GetSessionTokenResponse sessionTokenResponse =
await stsClient.GetSessionTokenAsync(getSessionTokenRequest); // error twrown from this line
Credentials credentials = sessionTokenResponse.Credentials;
return credentials;
IAM role is working fine when creating new AmazonS3Client(region)
Solution
IAM roles cannot get session tokens, only users and accounts can.
If you want to retrieve the same credentials as a normal credential resolution chain would (on EC2, they are normally retrieved from the metadata endpoint), you can use FallbackCredentialsFactory.GetCredentials()
.
It's a static method which will give you the same set of temporary credentials that the rest of AWS SDK clients will be using if constructed without parameters.
If you want to assume another role, or even the same role with duration or policies different from what your EC2 instance was given, then you should call AssumeRole
.
Answered By - Quassnoi Answer Checked By - Marie Seifert (WPSolving Admin)