

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# を使用してコードで認証情報を指定する 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 アイデンティティセンター により、ID (ユーザー) は次の 2 つのオペレーションを実行できます。

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>

次の信頼ポリシーは、前の例で委任されたロールにアタッチされています。このポリシーでは、2 つのアカウントの ID (ユーザー) がロールを委任されることができます。

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

****  

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

------