範本程式碼:使用多重要素驗證請求憑證 - AWS Identity and Access Management

範本程式碼:使用多重要素驗證請求憑證

以下範例顯示如何呼叫 GetSessionTokenAssumeRole 操作,並傳遞 MFA 驗證參數。呼叫 GetSessionToken 不需要許可,但您必須擁有一個可讓您呼叫 AssumeRole 的政策。傳回的憑證隨後用於列出帳戶中的所有 S3 儲存貯體。

使用 MFA 身分驗證呼叫 GetSessionToken

以下範例說明如何呼叫 GetSessionToken 並傳遞 MFA 身分驗證資訊。然後,由 GetSessionToken 操作傳回的臨時安全憑證用於列出帳戶中的所有 S3 儲存貯體。

連接到執行此程式碼的使用者的政策 (或群組中的使用者),會針對傳回的臨時憑證提供許可。對於此範本程式碼,政策必須授予使用者許可來請求 Amazon S3 ListBuckets 操作。

下列程式碼範例示範如何透過 AWS STS 取得工作階段字符,並使用它來執行需要 MFA 字符的服務動作。

Python
SDK for Python (Boto3)
提示

若要瞭解如何設定和執行此範例,請參閱 GitHub

透過傳遞 MFA 字符取得工作階段字符,並使用它列出該帳戶的 Amazon S3 儲存貯體。

def list_buckets_with_session_token_with_mfa(mfa_serial_number, mfa_totp, sts_client): """ Gets a session token with MFA credentials and uses the temporary session credentials to list Amazon S3 buckets. Requires an MFA device serial number and token. :param mfa_serial_number: The serial number of the MFA device. For a virtual MFA device, this is an Amazon Resource Name (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. """ if mfa_serial_number is not None: response = sts_client.get_session_token( SerialNumber=mfa_serial_number, TokenCode=mfa_totp) else: response = sts_client.get_session_token() temp_credentials = response['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"Buckets for the account:") for bucket in s3_resource.buckets.all(): print(bucket.name)
  • 如需 API 詳細資訊,請參閱《AWS SDK for Python (Boto3) API 參考》中的 GetSessionToken

使用 MFA 身分驗證呼叫 AssumeRole

以下範例說明如何呼叫 AssumeRole 並傳遞 MFA 身分驗證資訊。然後,由 AssumeRole 傳回的臨時安全憑證用於列出帳戶中的所有 Amazon S3 儲存貯體。

如需有關此案例的詳細資訊,請參閱 使用案例:跨帳戶委派的 MFA 防護

下列程式碼範例示範如何透過 AWS STS 擔任角色。

JavaScript
SDK for JavaScript V3
提示

若要瞭解如何設定和執行此範例,請參閱 GitHub

建立用戶端。

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 詳細資訊,請參閱《AWS SDK for JavaScript API 參考》中的 AssumeRole

適用於 JavaScript 的 SDK 第 2 版
提示

若要瞭解如何設定和執行此範例,請參閱 GitHub

// 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 詳細資訊,請參閱《AWS SDK for JavaScript API 參考》中的 AssumeRole

Python
SDK for Python (Boto3)
提示

若要瞭解如何設定和執行此範例,請參閱 GitHub

擔任需要 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 詳細資訊,請參閱《AWS SDK for Python (Boto3) API 參考》中的 AssumeRole

Ruby
適用於 Ruby 的 SDK
提示

若要瞭解如何設定和執行此範例,請參閱 GitHub

# 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 詳細資訊,請參閱《AWS SDK for Ruby API 參考》中的 AssumeRole