AWS STS 使用 JavaScript (v3)SDK的示例 - AWS SDK 程式碼範例

AWS 文檔 AWS SDK示例 GitHub 回購中有更多SDK示例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

AWS STS 使用 JavaScript (v3)SDK的示例

下列程式碼範例說明如何使用 AWS SDK for JavaScript (v3) 搭配使用來執行動作及實作常見案例 AWS STS。

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數,但您可以在其相關情境和跨服務範例中查看內容中的動作。

Scenarios (案例) 是向您展示如何呼叫相同服務中的多個函數來完成特定任務的程式碼範例。

每個範例都包含一個連結 GitHub,您可以在其中找到如何在內容中設定和執行程式碼的指示。

主題

動作

下列程式碼範例會示範如何使用AssumeRole

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

建立用戶端。

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

假設IAM角色。

import { AssumeRoleCommand } from "@aws-sdk/client-sts"; import { client } from "../libs/client.js"; export const main = async () => { try { // Returns a set of temporary security credentials that you can use to // access Amazon Web Services resources that you might not normally // have access to. const command = new AssumeRoleCommand({ // The Amazon Resource Name (ARN) of the role to assume. RoleArn: "ROLE_ARN", // An identifier for the assumed role session. RoleSessionName: "session1", // The duration, in seconds, of the role session. The value specified // can range from 900 seconds (15 minutes) up to the maximum session // duration set for the role. DurationSeconds: 900, }); const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };
  • 如需詳API細資訊,請參閱AWS SDK for JavaScript API參考AssumeRole中的。

SDK對於 JavaScript (第 2 個)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

// 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中的。