使用 Amazon 开发工具包代入具有 Amazon STS 的角色 - Amazon Identity and Access Management
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

使用 Amazon 开发工具包代入具有 Amazon STS 的角色

以下代码示例演示了如何代入具有 Amazon STS 的角色。

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

using Amazon; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; using System; using System.Threading.Tasks; namespace AssumeRoleExample { class AssumeRole { /// <summary> /// This example shows how to use the AWS Security Token /// Service (AWS STS) to assume an IAM role. /// /// NOTE: It is important that the role that will be assumed has a /// trust relationship with the account that will assume the role. /// /// Before you run the example, you need to create the role you want to /// assume and have it trust the IAM account that will assume that role. /// /// See https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html /// for help in working with roles. /// </summary> private static readonly RegionEndpoint REGION = RegionEndpoint.USWest2; static async Task Main() { // Create the SecurityToken client and then display the identity of the // default user. var roleArnToAssume = "arn:aws:iam::123456789012:role/testAssumeRole"; var client = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(REGION); // Get and display the information about the identity of the default user. var callerIdRequest = new GetCallerIdentityRequest(); var caller = await client.GetCallerIdentityAsync(callerIdRequest); Console.WriteLine($"Original Caller: {caller.Arn}"); // Create the request to use with the AssumeRoleAsync call. var assumeRoleReq = new AssumeRoleRequest() { DurationSeconds = 1600, RoleSessionName = "Session1", RoleArn = roleArnToAssume }; var assumeRoleRes = await client.AssumeRoleAsync(assumeRoleReq); // Now create a new client based on the credentials of the caller assuming the role. var client2 = new AmazonSecurityTokenServiceClient(credentials: assumeRoleRes.Credentials); // Get and display information about the caller that has assumed the defined role. var caller2 = await client2.GetCallerIdentityAsync(callerIdRequest); Console.WriteLine($"AssumedRole Caller: {caller2.Arn}"); } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 AssumeRole

C++
SDK for C++
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

bool AwsDoc::STS::assumeRole(const Aws::String &roleArn, const Aws::String &roleSessionName, const Aws::String &externalId, Aws::Auth::AWSCredentials &credentials, const Aws::Client::ClientConfiguration &clientConfig) { Aws::STS::STSClient sts(clientConfig); Aws::STS::Model::AssumeRoleRequest sts_req; sts_req.SetRoleArn(roleArn); sts_req.SetRoleSessionName(roleSessionName); sts_req.SetExternalId(externalId); const Aws::STS::Model::AssumeRoleOutcome outcome = sts.AssumeRole(sts_req); if (!outcome.IsSuccess()) { std::cerr << "Error assuming IAM role. " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Credentials successfully retrieved." << std::endl; const Aws::STS::Model::AssumeRoleResult result = outcome.GetResult(); const Aws::STS::Model::Credentials &temp_credentials = result.GetCredentials(); // Store temporary credentials in return argument. // Note: The credentials object returned by assumeRole differs // from the AWSCredentials object used in most situations. credentials.SetAWSAccessKeyId(temp_credentials.GetAccessKeyId()); credentials.SetAWSSecretKey(temp_credentials.GetSecretAccessKey()); credentials.SetSessionToken(temp_credentials.GetSessionToken()); } return outcome.IsSuccess(); }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 AssumeRole

JavaScript
SDK for JavaScript V3
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

创建客户端。

import { STSClient } from "@aws-sdk/client-sts"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon STS service client object. const stsClient = new STSClient({ region: REGION }); export { stsClient };

代入 IAM 角色。

// Import required AWS SDK clients and commands for Node.js import { stsClient } from "./libs/stsClient.js"; import { AssumeRoleCommand, GetCallerIdentityCommand, } from "@aws-sdk/client-sts"; // Set the parameters export const params = { RoleArn: "ARN_OF_ROLE_TO_ASSUME", //ARN_OF_ROLE_TO_ASSUME RoleSessionName: "session1", DurationSeconds: 900, }; export const run = async () => { try { //Assume Role const data = await stsClient.send(new AssumeRoleCommand(params)); return data; const rolecreds = { accessKeyId: data.Credentials.AccessKeyId, secretAccessKey: data.Credentials.SecretAccessKey, sessionToken: data.Credentials.SessionToken, }; //Get Amazon Resource Name (ARN) of current identity try { const stsParams = { credentials: rolecreds }; const stsClient = new STSClient(stsParams); const results = await stsClient.send( new GetCallerIdentityCommand(rolecreds) ); console.log("Success", results); } catch (err) { console.log(err, err.stack); } } catch (err) { console.log("Error", err); } }; run();
  • 有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 AssumeRole

SDK for JavaScript V2
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

// Load the AWS SDK for Node.js const AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); var roleToAssume = {RoleArn: 'arn:aws:iam::123456789012:role/RoleName', RoleSessionName: 'session1', DurationSeconds: 900,}; var roleCreds; // Create the STS service object var sts = new AWS.STS({apiVersion: '2011-06-15'}); //Assume Role sts.assumeRole(roleToAssume, function(err, data) { if (err) console.log(err, err.stack); else{ roleCreds = {accessKeyId: data.Credentials.AccessKeyId, secretAccessKey: data.Credentials.SecretAccessKey, sessionToken: data.Credentials.SessionToken}; stsGetCallerIdentity(roleCreds); } }); //Get Arn of current identity function stsGetCallerIdentity(creds) { var stsParams = {credentials: creds }; // Create STS service object var sts = new AWS.STS(stsParams); sts.getCallerIdentity({}, function(err, data) { if (err) { console.log(err, err.stack); } else { console.log(data.Arn); } }); }
  • 有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 AssumeRole

Python
适用于 Python (Boto3) 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

代入需要 MFA 令牌的 IAM 角色并使用临时凭证列出该账户的 Amazon S3 存储桶。

def list_buckets_from_assumed_role_with_mfa( assume_role_arn, session_name, mfa_serial_number, mfa_totp, sts_client): """ Assumes a role from another account and uses the temporary credentials from that role to list the Amazon S3 buckets that are owned by the other account. Requires an MFA device serial number and token. The assumed role must grant permission to list the buckets in the other account. :param assume_role_arn: The Amazon Resource Name (ARN) of the role that grants access to list the other account's buckets. :param session_name: The name of the STS session. :param mfa_serial_number: The serial number of the MFA device. For a virtual MFA device, this is an ARN. :param mfa_totp: A time-based, one-time password issued by the MFA device. :param sts_client: A Boto3 STS instance that has permission to assume the role. """ response = sts_client.assume_role( RoleArn=assume_role_arn, RoleSessionName=session_name, SerialNumber=mfa_serial_number, TokenCode=mfa_totp) temp_credentials = response['Credentials'] print(f"Assumed role {assume_role_arn} and got temporary credentials.") s3_resource = boto3.resource( 's3', aws_access_key_id=temp_credentials['AccessKeyId'], aws_secret_access_key=temp_credentials['SecretAccessKey'], aws_session_token=temp_credentials['SessionToken']) print(f"Listing buckets for the assumed role's account:") for bucket in s3_resource.buckets.all(): print(bucket.name)
  • 有关 API 详细信息,请参阅《Amazon SDK for Python(Boto3)API 参考》中的 AssumeRole

Ruby
SDK for Ruby
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

# Creates an AWS Security Token Service (AWS STS) client with specified credentials. # This is separated into a factory function so that it can be mocked for unit testing. # # @param key_id [String] The ID of the access key used by the STS client. # @param key_secret [String] The secret part of the access key used by the STS client. def create_sts_client(key_id, key_secret) Aws::STS::Client.new(access_key_id: key_id, secret_access_key: key_secret) end # Gets temporary credentials that can be used to assume a role. # # @param role_arn [String] The ARN of the role that is assumed when these credentials # are used. # @param sts_client [AWS::STS::Client] An AWS STS client. # @return [Aws::AssumeRoleCredentials] The credentials that can be used to assume the role. def assume_role(role_arn, sts_client) credentials = Aws::AssumeRoleCredentials.new( client: sts_client, role_arn: role_arn, role_session_name: "create-use-assume-role-scenario" ) puts("Assumed role '#{role_arn}', got temporary credentials.") credentials end
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 AssumeRole

有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。