How to Switch Roles Using AWS SDK on C#

Asked 1 years ago, Updated 1 years ago, 338 views

I am currently working on a C# app for AWS access, but I have been stuck switching roles.
I looked up various sites including official AWS information and language differences, but I didn't see anything used in conjunction with MFA, so I didn't understand the reason for the failure.
I apologize for the lack of understanding of the basics, but if anyone knows how to implement it, please let me know.

Current state

  • I have multiple AWS accounts, one of which uses Role.
  • All accounts use MFA to access AWS.
  • The role you want to use does not have an ExternalId.
  • Authentication with accounts that do not use the Role has been successful and S3 access has been verified.
  • Services using the CLI can run with Role.
  • As a result of research, I think I will use the AssumeRoleRequest function, but I don't know when to use it.
  • Different locations (for example, before MFA authentication)
  • As far as the message is concerned, it may not have been possible to switch roles with MFA authenticated users as root users
  • You may need to specify the function of S3 every time you run it in the form of a --profile test as used in the CLI

The following is the code and other information.Some code has been omitted (:) and sensitive information has been rewritten.

AWS Information

AWS Account

RootUserID=9876-5432-1098
[email protected]

RoleUserID=0123-4567-8901
RoleUserName = Test_Role_User

Trusted entities

{
  "version": 2012-10-17
  "Statement": [
    {
      "Effect": "Allow"
      "Principal": {
         "AWS": "arn:aws:iam::987654321098:root"
       },
      "Action": "sts:AssumeRole",
      "Condition": {}
    }
  ]
}

Local file *Available in CLI.

<.aws\credentials>
[default]
aws_access_key_id = ABCDEGHOJKLM
aws_secret_access_key=11AA22bb33CC44dd
region=ap-northeast-1

<.aws\config>
[default]
region=ap-northeast-1
output = json

[profile test]
role_arn=arn:aws:iam::012345678901:role/Test_Role_User
source_profile=default
region=ap-northeast-1

Code C#

//AWSSDK.Core version 3.3.0.0 Runtimeversionv4.0.30319
// AWSSDK.S3 version 3.3.0.0 Runtimeversionv4.0.30319
// AWSSDK.SecurityToken version 3.3.0.0 Runtimeversionv4.0.30319
//.netframework 4.6.2
:
using Amazon;
using Amazon.Runtime.CredentialManagement;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfar;
using Amazon.S3.IO

namespace AWSTool
{
 public class AWSAAccess{
  
   public static async Task AWSAuth()
   {
     varcredOption=newCredentialProfileOption();
     varcredentialsFile = new SharedCredentialsFile();
     credOption.AccessKey="ABCDEGHOJKLM";
     credOptionSecretKey="11AA22bb33CC44dd";
     var profile=new CredentialProfile("default",credOption);
     profile.Region=RegionEndpoint.GetBySystemName("ap-northeast-1");
     credentialsFile.RegisterProfile(profile);
     if(credentialsFile.TryGetProfile("default", outprofile) == false)
        Console.WriteLine("Profile name not found")
     
     AWSCredentialsawsCredentials=null;
     if(AWSCredentialsFactory.TryGetAWSCredentials(profile,credentialsFile,outawsCredentials)== 
 false)
        Console.WriteLine("Certificate Generation Failed")

   string Token="XXXXXX" // Token code generated by another library
      varstsClient=new AmazonSecurityTokenServiceClient();
      vargetSessionRequest=newGetSessionTokenRequest();
      getSessionRequest.DurationSeconds = 3600;
      getSessionRequest.SerialNumber="arn:aws:iam::987654321098:mfa/[email protected]"
      getSessionRequest.TokenCode="XXXXX"
      GetSessionTokenResponse getSessionTolenResponse=stsClient.GetSessionToken(getSessionTokenRequest);
      
      string tempAccessKeyId = getSessionTokenResponse.Credentials.AccessKeyId;
      string tempSessionAccessKey = GetSessionTokenResponse.Credentials.SecretAccessKey;
      string tempSessionToken=getSessionTokenResponse.Credentials.SessionToken;
      SessionAWSCredentials tempCredentials = new SessionAWSCredentials (tempAccessKeyId, tempSessionAccessKey, tempSessionToken)
      
      // AsumeRole after MFA authentication From here
        AssumeRoleRequest AssumeRoleRequest = new AssumeRoleRequest()
        {
           DurationSeconds = 1600,
           RoleArn="arn:aws:iam::012345678901:role/Test_Role_User",
           RoleSessionName = "TestSession"
        }
        var RoleResponse=awatstsClient.AssumeRoleAsync (AssumeRoleRequest);
        // ↑ The following message failed here:
    // User:arn:aws:iam::987654321098:user/[email protected] is not authorized to perform:sts:AssumeRole on resource arn:aws:iam::012345678901::role/Test_Role_User
        
      // That's it
      
      varAWSS3 client = new AmazonS3 Client (tempCredentials);
      AWSS3GetBucketList (AWSS3 client); // Get S3 bucket list with another function

   }
 :
 }
}

c# aws-sdk

2022-12-06 23:44

1 Answers

First of all, I think it would be better to sort out the following differences.
·AWS account root account
·IAM users in each AWS account
·IAM role for each AWS account

Then, who is trying to do the Assume Role?

Under the root account of AWS account "9876-5432-1098",
"I understand that you are trying to switch to the IAM role ""Test_Role_User"" in the AWS account ""012345678901", is that correct?"

Assuming that.

User:arn:aws:iam::987654321098:user/[email protected] is not authorized to perform:sts:AssumeRole on resource arn:aws:iam::012345678901::role/Test_Role_User

The error message reads that authentication is successful as the caller, but you do not have permission to AssumeRole.

Since the caller is "user", it seems that the first thing you are trying to do is not the root account, but an IAM user named "[email protected]".Have you created an IAM user called [email protected]?Also, isn't the specified access key or secret access key for that IAM user?

The root account has full privileges, but the IAM user has only explicitly configured privileges.Therefore, the error appears to be that you do not have permission.

Since it is not recommended to assign an access key or a secret access key to the root account, it would be better to change it to a prerequisite that IAM users operate instead of calling the API with the root account.If this is the case, it should be possible to resolve the issue by granting IAM users permission to Assume Role in the IAM policy.The policy is described in the following document:
https://docs.aws.amazon.com/ja_jp/IAM/latest/UserGuide/id_roles_use_permissions-to-switch.html

Also, I think it is better to organize the setting status of MFA.Are you configuring MFA for the root account, MFA for the IAM user, or both?Even if an MFA is assigned to the root account or IAM user, you typically only need to specify an MFA one-time code when you log into the AWS console, and you are not prompted for an MFA when working with an access key or a secret access key.An exception is when condition specifies that MFA usage is mandatory for IAM users when granting permissions in the IAM policy, as described in the document below.
https://docs.aws.amazon.com/ja_jp/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html#MFAProtectedAPI-user-mfa

Probably not configured for such an IAM policy, so MFA is not required for API calls with access keys and secret access keys.(There is a possibility that such an IAM policy has been set and the MFA's one-time code has not been properly passed, resulting in a lack of permission error, but I am sure that is not the case.)

MFA's one-time code changes periodically, so it's not realistic to put it in the C# code, and even if you can change it with arguments, it's not appropriate to use MFA even though it's used as a code for automatic processing.I think it's better to secure the execution environment as a whole by other means such as using EC2 roles.

Also, it is better to avoid putting access keys and secret keys in the code.The key is often leaked when something happens, such as a source code repository.In the first place, if the configuration file is loaded properly, the key should not need to be specified by code.


2022-12-07 00:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.