AWS Assume Role via .Net SDK gives Access Denied but works with CLI

0

I am trying to upload a file in S3 by AWS Assume Role. When I am trying to access it from CLI it works fine but from .Net SDK it gives me Access Denied error.

Here are the steps I followed in CLI -

  1. Setup the access key/secret key for user using aws configure
  2. Assume the Role - “aws sts assume-role --role-arn "arn:aws:iam::1010101010:role/Test-Account-Role" --role-session-name AWSCLI-Session”
  3. Take the access key / secret key / session token from the assumed role and setup an AWS profile. The credentials are printed out/returned from the assumed role.
  4. Switch to the assume role profile: “set AWS_PROFILE=<TempRole>
  5. Verify that the user has the role: “aws sts get-caller-identity”
  6. Access the bucket using ls or cp or rm command - Works Successfully.

Now I am trying to access it from .Net core App -

Here is the code snippet- Note that I am using same Access and Secret key as CLI from my local.

        try
        {
            var region = RegionEndpoint.GetBySystemName(awsRegion);

            SessionAWSCredentials tempCredentials = await GetTemporaryCredentialsAsync(awsAccessKey, awsSecretKey, region, roleARN);

            //Use the temp credentials received to create the new client
            IAmazonS3 client = new AmazonS3Client(tempCredentials, region);
            
            TransferUtility utility = new TransferUtility(client);
            // making a TransferUtilityUploadRequest instance
            TransferUtilityUploadRequest request = new TransferUtilityUploadRequest
            {
                BucketName = bucketName, 
                Key = $"{subFolder}/{fileName}", 
                FilePath = localFilePath 
            utility.Upload(request); //transfer
            fileUploadedSuccessfully = true;

        }
        catch (AmazonS3Exception ex)
        {
            // HandleException
        }
        catch (Exception ex)
        {
             // HandleException
        }

The method to get temp credentials is as follow - GetTemporaryCredentialsAsync

  private static async Task<SessionAWSCredentials> GetTemporaryCredentialsAsync(string awsAccessKey, string awsSecretKey, RegionEndpoint region, string roleARN)
        {
            using (var stsClient = new AmazonSecurityTokenServiceClient(awsAccessKey, awsSecretKey, region))
            {

                var getSessionTokenRequest = new GetSessionTokenRequest
                {
                    DurationSeconds = 7200
                };

                await stsClient.AssumeRoleAsync(
                    new AssumeRoleRequest()
                    {
                        RoleArn = roleARN,
                        RoleSessionName = "mySession"
                    });

                GetSessionTokenResponse sessionTokenResponse =
                              await stsClient.GetSessionTokenAsync(getSessionTokenRequest);

                Credentials credentials = sessionTokenResponse.Credentials;

                var sessionCredentials =
                    new SessionAWSCredentials(credentials.AccessKeyId,
                                              credentials.SecretAccessKey,
                                              credentials.SessionToken);
                return sessionCredentials;
            }
        }

I am getting back the temp credentials but it gives me Access Denied while uploading the file. Not sure if I am missing anything here.

Also noted that the token generated via SDK is shorter than that from CLI. I tried pasting these temp credentials to local profile and then tried to access the bucket and getting the Access Denied error then too.

1 Resposta
0

Have you tried some other api call and checked what CloudTrail says the role was that you used in .Net? We faced some odd problems long ago in .Net Core / 5.0+ where the main credentials were not what we expected due to something not initializing correctly - Sorry, I don't recall the exact details - But CloudTrail will show the user you are authenticated as for non S3 calls (unless you have S3 calls logged).

profile picture
respondido há um ano

Você não está conectado. Fazer login para postar uma resposta.

Uma boa resposta responde claramente à pergunta, dá feedback construtivo e incentiva o crescimento profissional de quem perguntou.

Diretrizes para responder a perguntas