

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

# 使用 TIP 外掛程式存取 AWS 服務
<a name="access-tip"></a>

 信任的身分傳播 (TIP) 是 的一項功能 AWS IAM Identity Center ，可讓 的管理員根據 群組關聯等使用者屬性 AWS 服務 授予許可。透過受信任的身分傳播，身分內容會新增至 IAM 角色，以識別請求存取 AWS 資源的使用者。此內容會傳播到其他 AWS 服務。

 身分內容包含的資訊， AWS 服務 用於在收到存取請求時做出授權決策。此資訊包含識別請求者的中繼資料 （例如，IAM Identity Center 使用者）、請求存取的 AWS 服務 （例如，Amazon Redshift)，以及存取範圍 （例如，唯讀存取）。接收 AWS 服務 使用此內容，以及指派給使用者的任何許可，來授權存取其資源。如需詳細資訊，請參閱 AWS IAM Identity Center 《 使用者指南》中的[信任身分傳播概觀中的 ](https://docs.aws.amazon.com/singlesignon/latest/userguide/trustedidentitypropagation-overview.html)。

 TIP 外掛程式可與支援受信任身分傳播 AWS 服務 的 搭配使用。做為參考使用案例，請參閱《[Amazon Q Business 使用者指南》中的使用 設定 AWS IAM Identity Center](https://docs.aws.amazon.com/amazonq/latest/qbusiness-ug/create-application.html) *Amazon Q Business* 應用程式。

**注意**  
 如果您使用的是 Amazon Q Business，請參閱[使用 設定 Amazon Q Business 應用程式 AWS IAM Identity Center](https://docs.aws.amazon.com/amazonq/latest/qbusiness-ug/create-application.html)以取得服務特定指示。

## 使用 TIP 外掛程式的先決條件
<a name="prereq-tip"></a>

需要下列資源，外掛程式才能運作：

1. 您必須使用 適用於 Java 的 AWS SDK 或 適用於 JavaScript 的 AWS SDK。

1. 確認您正在使用的服務支援信任的身分傳播。

   請參閱《 *AWS IAM Identity Center 使用者指南*》中[AWS 透過與](https://docs.aws.amazon.com/singlesignon/latest/userguide/awsapps-that-work-with-identity-center.html) **IAM Identity Center 整合之受管應用程式的 IAM Identity Center 啟用受信任身分傳播**欄。

1. 啟用 IAM Identity Center 和信任的身分傳播。

   請參閱*AWS IAM Identity Center 《 使用者指南*》中的 [TIP 先決條件和考量](https://docs.aws.amazon.com/singlesignon/latest/userguide/trustedidentitypropagation-overall-prerequisites.html)事項。

1. 您必須擁有 Identity-Center-integrated的應用程式。

   請參閱*AWS IAM Identity Center 《 使用者指南*》中的[AWS 受管應用程式](https://docs.aws.amazon.com/singlesignon/latest/userguide/awsapps-quick-start-setting-up-identity-center-to-test-awsmanagedapps.html)或[客戶受管應用程式](https://docs.aws.amazon.com/singlesignon/latest/userguide/customermanagedapps-trusted-identity-propagation-set-up-your-own-app-OAuth2.html)。

1. 您必須設定信任的權杖發行者 (TTI)，並將您的服務連線至 IAM Identity Center。

   請參閱《 *AWS IAM Identity Center 使用者指南*》中[設定](https://docs.aws.amazon.com/singlesignon/latest/userguide/setuptrustedtokenissuer.html#setuptrustedtokenissuer-tasks)[信任權杖發行者的先決條件](https://docs.aws.amazon.com/singlesignon/latest/userguide/using-apps-with-trusted-token-issuer.html#trusted-token-issuer-prerequisites)和任務。

## 在程式碼中使用 TIP 外掛程式
<a name="using-tip"></a>

1. 建立信任身分傳播外掛程式的執行個體。

1. 建立服務用戶端執行個體以與您的 互動， AWS 服務 並透過新增信任的身分傳播外掛程式來自訂服務用戶端。

TIP 外掛程式採用下列輸入參數：
+ **`webTokenProvider`**：客戶實作以從外部身分提供者取得 OpenID 字符的函數。
+ **`accessRoleArn`**：由具有使用者身分內容的外掛程式擔任的 IAM 角色 ARN，以取得身分增強憑證。
+ **`applicationArn`**：用戶端或應用程式的唯一識別符字串。此值是已設定 OAuth 授予的應用程式 ARN。
+ **`ssoOidcClient`**：（選用） SSO OIDC 用戶端，例如[https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/ssooidc/SsoOidcClient.html](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/ssooidc/SsoOidcClient.html)適用於 Java 的 或[https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sso-oidc/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sso-oidc/)適用於 JavaScript 的 ，具有客戶定義的組態。若未提供，則會使用 `applicationRoleArn` 建立並啟用預設的 OIDC 用戶端。
+  **`stsClient`**：（選用） AWS STS 具有客戶定義組態的用戶端，用於`accessRoleArn`以使用者的身分內容擔任 。如果未提供，`applicationRoleArn`則會執行個體化並使用 的 AWS STS 用戶端。
+ **`applicationRoleArn`**：（選用） 要擔任的 IAM 角色 ARN，`AssumeRoleWithWebIdentity`以便可以引導 OIDC 和 AWS STS 用戶端。
  + 如果未提供，則必須**同時**提供 `ssoOidcClient`和 `stsClient` 參數。
  + 如果提供， `applicationRoleArn`不能與 `accessRoleArn` 參數的值相同。 `applicationRoleArn` 用於建置 stsClient，其用於擔任 accessRole。如果 `applicationRole`和 都使用相同的角色`accessRole`，則表示使用角色來擔任自己 （自我角色假設），這會不建議這麼做 AWS。如需詳細資訊，請參閱[公告](https://aws.amazon.com/blogs/security/announcing-an-update-to-iam-role-trust-policy-behavior/)。

### `ssoOidcClient`、 `stsClient`和 `applicationRoleArn` 參數的考量事項
<a name="considerations-tip"></a>

設定 TIP 外掛程式時，請根據您提供的參數，考慮下列許可要求：
+ 如果您要提供 `ssoOidcClient`和 `stsClient`：
  + 上的登入資料`ssoOidcClient`應具有呼叫身分中心的`oauth:CreateTokenWithIAM`許可，以取得身分中心特定的使用者內容。
  + 上的登入資料`stsClient`應具有 `sts:AssumeRole`和 上的`sts:SetContext`許可`accessRole`。 `accessRole`也需要設定與 上登入資料的信任關係`stsClient`。
+ 如果您要提供 `applicationRoleArn`：
  + `applicationRole` 應該具有必要資源 (IdC 執行個體 `accessRole`) 的 `oauth:CreateTokenWithIAM``sts:AssumeRole`和 `sts:SetContext`許可，因為它將用於建置 OIDC 和 STS 用戶端。
  + `applicationRole` 應與用於產生 的身分提供者具有信任關係`webToken`，因為 `webToken`將用於透過外掛程式的 [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) 呼叫擔任 applicationRole。

**ApplicationRole 組態範例：**

具有 Web 權杖提供者的信任政策：

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "arn:aws:iam::ACCOUNT_ID:oidc-provider/IDENTITY_PROVIDER_URL"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "IDENTITY_PROVIDER_URL:aud": "CLIENT_ID_TO_BE_TRUSTED"
                }
            }
        }
    ]
}
```

許可政策：

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "sts:AssumeRole",
                "sts:SetContext"
            ],
            "Resource": [
                "accessRoleArn"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "sso-oauth:CreateTokenWithIAM"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

## 使用 TIP 的程式碼範例
<a name="tip-code-example"></a>

以下範例示範如何使用 適用於 Java 的 AWS SDK 或 在程式碼中實作 TIP 外掛程式 適用於 JavaScript 的 AWS SDK。

------
#### [ Java ]

若要在 適用於 Java 的 AWS SDK 專案中使用 TIP 外掛程式，您需要在專案的 `pom.xml`檔案中將其宣告為相依性。

```
<dependency>
<groupId>software.amazon.awsidentity.trustedIdentityPropagation</groupId>
<artifactId>aws-sdk-java-trustedIdentityPropagation-java-plugin</artifactId>
   <version>2.0.0</version>
</dependency>
```

在您的原始程式碼中，包含 所需的套件陳述式`software.amazon.awssdk.trustedidentitypropagation`。

下列範例顯示建立受信任身分傳播外掛程式執行個體並將其新增至服務用戶端的兩種方式。這兩個範例都使用 Amazon S3 做為服務，並使用 `S3AccessGrantsPlugin` 來管理使用者特定許可，但可以套用到支援受信任身分傳播 (TIP) 的任何 AWS 服務 。

**注意**  
對於這些範例，您需要從 S3 Access Grants 設定使用者特定許可。如需詳細資訊，請參閱 [S3 Access Grants 文件](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-grants.html)。

**選項 1：建置並傳遞 OIDC 和 STS 用戶端**

```
SsoOidcClient oidcClient = SsoOidcClient.builder()
    .region(Region.US_EAST_1)
    .credentialsProvider(credentialsProvider).build();

StsClient stsClient = StsClient.builder()
    .region(Region.US_EAST_1)
    .credentialsProvider(credentialsProvider).build();

TrustedIdentityPropagationPlugin trustedIdentityPropagationPlugin = TrustedIdentityPropagationPlugin.builder()
        .webTokenProvider(() -> webToken)
        .applicationArn(idcApplicationArn)
        .accessRoleArn(accessRoleArn)
        .ssoOidcClient(oidcClient)
        .stsClient(stsClient)
        .build();

S3AccessGrantsPlugin accessGrantsPlugin = S3AccessGrantsPlugin.builder()
        .build();

S3Client s3Client =
        S3Client.builder().region(Region.US_EAST_1)
                .crossRegionAccessEnabled(true)
                .addPlugin(trustedIdentityPropagationPlugin)
                .addPlugin(accessGrantsPlugin)
                .build();

final var resp = s3Client.getObject(GetObjectRequest.builder()
        .key("path/to/object/fileName")
        .bucket("bucketName")
        .build());
```

**選項 2：將 applicationRoleArn 和延遲用戶端建立傳遞至外掛程式**

```
TrustedIdentityPropagationPlugin trustedIdentityPropagationPlugin = TrustedIdentityPropagationPlugin.builder()
        .webTokenProvider(() -> webToken)
        .applicationArn(idcApplicationArn)
        .accessRoleArn(accessRoleArn)
        .applicationRoleArn(applicationRoleArn)
        .build();

S3AccessGrantsPlugin accessGrantsPlugin = S3AccessGrantsPlugin.builder()
        .build();

S3Client s3Client =
        S3Client.builder().region(Region.US_EAST_1)
                .crossRegionAccessEnabled(true)
                .addPlugin(trustedIdentityPropagationPlugin)
                .addPlugin(accessGrantsPlugin)
                .build();

final var resp = s3Client.getObject(GetObjectRequest.builder()
        .key("path/to/object/fileName")
        .bucket("bucketName")
        .build());
```

如需其他詳細資訊和來源，請參閱 GitHub 上的 [ trusted-identity-propagation-java](https://github.com/aws-sdk-plugin/trusted-identity-propagation-java)。

------
#### [ JavaScript ]

執行下列命令，在您的 適用於 JavaScript 的 AWS SDK 專案中安裝 TIP 身分驗證外掛程式套件：

```
$  npm i @aws-sdk-extension/trusted-identity-propagation
```

最終`package.json`應包含類似如下的相依性：

```
  "dependencies": {
"@aws-sdk-extension/trusted-identity-propagation": "^2.0.0"
  },
```

 在您的原始程式碼中，匯入所需的`TrustedIdentityPropagationExtension`相依性。

 下列範例顯示建立受信任身分傳播外掛程式執行個體並將其新增至服務用戶端的兩種方式。這兩個範例都使用 Amazon S3 做為服務，並使用 Amazon S3 Access Grants 來管理使用者特定許可，但可以套用到支援受信任身分傳播 (TIP) 的任何 AWS 服務 。

**注意**  
如需這些範例，您需要從 Amazon S3 Access Grants 設定使用者特定許可，請參閱 [Amazon S3 Access Grants 文件](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-grants.html)以取得更多詳細資訊。

**選項 1：建置並傳遞 OIDC 和 STS 用戶端**

```
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { S3ControlClient, GetDataAccessCommand } from "@aws-sdk/client-s3-control";
import { TrustedIdentityPropagationExtension } from "@aws-sdk-extension/trusted-identity-propagation";

const s3ControlClient = new S3ControlClient({
    region: "us-east-1",
    extensions: [
        TrustedIdentityPropagationExtension.create({
            webTokenProvider: async () => {
                return 'ID_TOKEN_FROM_YOUR_IDENTITY_PROVIDER';
            },
            ssoOidcClient: customOidcClient,
            stsClient: customStsClient,
            accessRoleArn: accessRoleArn,
            applicationArn: applicationArn,
        }),
    ],
});

const getDataAccessParams = {
  Target: "S3_URI_PATH",
  Permission: "READ",
  AccountId: ACCOUNT_ID,
  InstanceArn: S3_ACCESS_GRANTS_ARN,
  TargetType: "Object",
};

try {
  const command = new GetDataAccessCommand(getDataAccessParams);
  const response = await s3ControlClient.send(command);

  const credentials = response.Credentials;

  // Create a new S3 client with the temporary credentials
  const temporaryS3Client = new S3Client({
    region: "us-east-1",
    credentials: {
      accessKeyId: credentials.AccessKeyId,
      secretAccessKey: credentials.SecretAccessKey,
      sessionToken: credentials.SessionToken,
    },
  });

  // Use the temporary S3 client to perform the operation
  const s3Params = {
    Bucket: "BUCKET_NAME",
    Key: "S3_OBJECT_KEY",
  };
  const getObjectCommand = new GetObjectCommand(s3Params);
  const s3Object = await temporaryS3Client.send(getObjectCommand);

  const fileContent = await s3Object.Body.transformToString();

  // Process the S3 object data
  console.log("Successfully retrieved S3 object:", fileContent);
} catch (error) {
  console.error("Error accessing S3 data:", error);
}
```

**選項 2：將 applicationRoleArn 和延遲用戶端建立傳遞至外掛程式**

```
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { S3ControlClient, GetDataAccessCommand } from "@aws-sdk/client-s3-control";
import { TrustedIdentityPropagationExtension } from "@aws-sdk-extension/trusted-identity-propagation";

const s3ControlClient = new S3ControlClient({
    region: "us-east-1",
    extensions: [
        TrustedIdentityPropagationExtension.create({
            webTokenProvider: async () => {
                return 'ID_TOKEN_FROM_YOUR_IDENTITY_PROVIDER';
            },
            accessRoleArn: accessRoleArn,
            applicationRoleArn: applicationRoleArn,
            applicationArn: applicationArn,
        }),
    ],
});

// Same S3 AccessGrants workflow as Option 1
const getDataAccessParams = {
  Target: "S3_URI_PATH",
  Permission: "READ",
  AccountId: ACCOUNT_ID,
  InstanceArn: S3_ACCESS_GRANTS_ARN,
  TargetType: "Object",
};

try {
  const command = new GetDataAccessCommand(getDataAccessParams);
  const response = await s3ControlClient.send(command);

  const credentials = response.Credentials;

  const temporaryS3Client = new S3Client({
    region: "us-east-1",
    credentials: {
      accessKeyId: credentials.AccessKeyId,
      secretAccessKey: credentials.SecretAccessKey,
      sessionToken: credentials.SessionToken,
    },
  });

  const s3Params = {
    Bucket: "BUCKET_NAME",
    Key: "S3_OBJECT_KEY",
  };
  const getObjectCommand = new GetObjectCommand(s3Params);
  const s3Object = await temporaryS3Client.send(getObjectCommand);

  const fileContent = await s3Object.Body.transformToString();

  console.log("Successfully retrieved S3 object:", fileContent);
} catch (error) {
  console.error("Error accessing S3 data:", error);
}
```

如需其他詳細資訊和來源，請參閱 GitHub 上的 [trusted-identity-propagation-js](https://github.com/aws-sdk-plugin/trusted-identity-propagation-js)。

------