本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
在代码中提供临时证书
如果默认凭证链或特定或自定义提供商或提供商链不适用于您的应用程序,则可以直接在代码中提供临时证书。这些可以是上面描述的 IAM 角色证书,也可以是从Amazon Security Token Service (Amazon STS) 检索的临时证书。如果您使用检索临时证书Amazon STS,请将其提供给Amazon Web Service客户端,如以下代码示例所示。
-
实例化提供AwsCredentials接口的类,例如AwsSessionCredentials。向其提供用于连接的Amazon访问密钥和会话令牌。
-
创建一个StaticCredentialsProvider对象并将其与该
AwsSessionCredentials
对象一起提供。 -
使用配置服务客户端生成器
StaticCredentialsProvider
并生成客户端。
以下示例使用您提供的临时证书创建 Amazon S3 服务客户端。
public static void assumeRole(String roleArn, String roleSessionName) { // The IAM role represented by the roleArn parameter can be assumed by any user in the same account // and has read-only permissions when it accesses Amazon S3. // The default credentials provider chain will find the single sign-on settings in the [default] profile. StsClient stsClient = StsClient.builder() .region(Region.US_EAST_1) .build(); try { AssumeRoleRequest roleRequest = AssumeRoleRequest.builder() .roleArn(roleArn) .roleSessionName(roleSessionName) .build(); AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest); Credentials tempRoleCredentials = roleResponse.credentials(); // The following temporary credential items are used when Amazon S3 is called String key = tempRoleCredentials.accessKeyId(); String secKey = tempRoleCredentials.secretAccessKey(); String secToken = tempRoleCredentials.sessionToken(); // List all buckets in the account using the temporary credentials retrieved by invoking assumeRole. Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsSessionCredentials.create(key, secKey, secToken))) .region(region) .build(); List<Bucket> buckets = s3.listBuckets().buckets(); for (Bucket bucket : buckets) { System.out.println("bucket name: " + bucket.name()); } } catch (StsException e) { System.err.println(e.getMessage()); System.exit(1); } }