翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
を使用してコードで認証情報を指定する AWS SDK for Java 2.x
デフォルトの認証情報チェーン、または特定あるいはカスタムのプロバイダーやプロバイダーチェーンがアプリケーションに対して機能しない場合は、一時的な認証情報をコードで直接指定できます。これらは、上記の IAM ロール認証情報、または AWS Security Token Service () から取得した一時的な認証情報ですAWS STS。を使用して一時的な認証情報を取得した場合は AWS STS、次のコード例に示すように、 AWS のサービス クライアントに渡します。
-
StsClient.assumeRole()
を呼び出してロールを委任されます。 -
StaticCredentialsProvider
オブジェクトを作成し、 AwsSessionCredentials
オブジェクトとともに提供します。 -
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); } }
で定義された次のアクセス許可セット AWS IAM Identity Center により、ID (ユーザー) は次の 2 つのオペレーションを実行できます。
-
Amazon Simple Storage Service の
GetObject
オペレーション。 -
AWS Security Token Serviceの
AssumeRole
オペレーション。
ロールを引き受けない場合は、この例に示した s3.listBuckets()
メソッドは失敗します。
委任されたロールのアクセス許可ポリシー
前の例で委任されたロールには、次のアクセス許可ポリシーがアタッチされています。このアクセス許可ポリシーにより、 はロールと同じアカウントのすべてのバケットを一覧表示できます。
委任されたロールの信頼ポリシー
次の信頼ポリシーは、前の例で委任されたロールにアタッチされています。このポリシーでは、2 つのアカウントの ID (ユーザー) がロールを委任されることができます。