

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

# 使用 在程式碼中提供登入資料 AWS SDK for Java 2.x
<a name="credentials-explicit"></a>

如果預設登入資料鏈或特定或自訂提供者或提供者鏈不適用於您的應用程式，您可以直接在程式碼中提供臨時登入資料。這些可以是[上述](credentials-temporary.md#credentials-temporary-from-portal)的 [IAM 角色登入](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtogetcredentials.html)資料，或從 AWS Security Token Service () 擷取的臨時登入資料AWS STS。如果您使用 擷取臨時登入資料 AWS STS，請將它們提供給 AWS 服務 用戶端，如下列程式碼範例所示。

1. 呼叫 以擔任角色`StsClient.assumeRole()`。

1. 建立 [StaticCredentialsProvider](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/StaticCredentialsProvider.html) 物件，並提供該`AwsSessionCredentials`物件。

1. 使用 設定服務用戶端建置器，`StaticCredentialsProvider`並建置用戶端。

下列範例使用 為 IAM 擔任的角色傳回 AWS STS 的臨時憑證建立 Amazon S3 服務用戶端。

```
    // The AWS IAM Identity Center identity (user) who executes this method does not have permission to list buckets.
    // The identity is configured in the [default] profile.
    public static void assumeRole(String roleArn, String roleSessionName) {
        // The IAM role represented by the 'roleArn' parameter can be assumed by identities in two different accounts
        // and the role permits the user to only list buckets.

        // The SDK's default credentials provider chain will find the single sign-on settings in the [default] profile.
        // The identity configured with the [default] profile needs permission to call AssumeRole on the STS service.
        try {
            Credentials tempRoleCredentials;
            try (StsClient stsClient = StsClient.create()) {
                AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
                        .roleArn(roleArn)
                        .roleSessionName(roleSessionName)
                        .build();

                AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
                tempRoleCredentials = roleResponse.credentials();
            }
            // Use the following temporary credential items for the S3 client.
            String key = tempRoleCredentials.accessKeyId();
            String secKey = tempRoleCredentials.secretAccessKey();
            String secToken = tempRoleCredentials.sessionToken();

            // List all buckets in the account associated with the assumed role
            // by using the temporary credentials retrieved by invoking stsClient.assumeRole().
            StaticCredentialsProvider staticCredentialsProvider = StaticCredentialsProvider.create(
                    AwsSessionCredentials.create(key, secKey, secToken));
            try (S3Client s3 = S3Client.builder()
                    .credentialsProvider(staticCredentialsProvider)
                    .build()) {
                List<Bucket> buckets = s3.listBuckets().buckets();
                for (Bucket bucket : buckets) {
                    System.out.println("bucket name: " + bucket.name());
                }
            }
        } catch (StsException | S3Exception e) {
            logger.error(e.getMessage());
            System.exit(1);
        }
    }
```

## 許可集
<a name="credentials-explicit-permission-set"></a>

中定義的下列許可集 AWS IAM Identity Center 允許身分 （使用者） 執行下列兩個操作

1. Amazon Simple Storage Service `GetObject`的操作。

1. `AssumeRole` 的操作 AWS Security Token Service。

如果不擔任角色，範例中顯示`s3.listBuckets()`的方法將會失敗。

------
#### [ JSON ]

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"s3:GetObject",
				"sts:AssumeRole"
			],
			"Resource": [
				"*"
			]
		}
	]
}
```

------

## 擔任的角色
<a name="credentials-explicit-role-to-assume"></a>

### 擔任的角色許可政策
<a name="credentials-explicit-role-policy"></a>

下列許可政策會連接到先前範例中擔任的角色。此許可政策允許列出與角色相同帳戶中的所有儲存貯體。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListAllMyBuckets"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

------

### 擔任的角色信任政策
<a name="credentials-explicit-trust-policy"></a>

下列信任政策會連接到先前範例中擔任的角色。此政策允許兩個帳戶中的身分 （使用者） 擔任該角色。

------
#### [ JSON ]

****  

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

------