

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 在代码中使用提供凭据 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 代入角色的临时证书创建 Amazon S3 服务客户端。 AWS STS 

```
    // 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.  AWS Security Token Service的 `AssumeRole` 操作。

如果不代入角色，则示例中显示的 `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": {}
        }
    ]
}
```

------