

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

# 在中指定特定的凭证提供商 AWS SDK for Java 2.x
<a name="credentials-providers"></a>

虽然默认凭证提供程序链在许多情况下都很方便，但明确指定凭证提供程序可以让您更好地控制身份验证行为、性能和安全性。

您可能想要指定凭证提供程序的原因可能包括：
+ 默认提供程序链按顺序检查多个来源，这样会增加延迟：

  ```
  // The default provider chain checks might check multiple sources until it finds
  // sufficient configuration.
  S3Client s3Client = S3Client.builder().build();
  
  // You can specify exactly where to look.
  S3Client optimizedClient = S3Client.builder()
      .credentialsProvider(InstanceProfileCredentialsProvider.create())
      .build();
  ```
+ 您需要使用非标准位置来访问凭证配置：

  ```
  // Use configuration from a custom file location.
  S3Client s3Client = S3Client.builder()
      .credentialsProvider(ProfileCredentialsProvider.builder()
              .profileFile(ProfileFile.builder()
                      .content(Paths.get("/custom/path/to/configuration/file"))
                      .type(ProfileFile.Type.CONFIGURATION) // Expects all non-default profiles to be prefixed with "profile".
                      .build())
              .profileName("custom")
              .build())
      .build();
  ```
+ 为不同服务客户端使用不同的凭证。例如，如果您的应用程序需要访问多个 AWS 账户或对不同的服务使用不同的权限：

  ```
  // S3 client using one set of credentials.
  S3Client s3Client = S3Client.builder()
      .credentialsProvider(ProfileCredentialsProvider.create("s3-readonly"))
      .build();
  
  // DynamoDB client using different credentials.
  DynamoDbClient dynamoDbClient = DynamoDbClient.builder()
      .credentialsProvider(ProfileCredentialsProvider.create("dynamodb-admin"))
      .build();
  ```
+ 控制凭证刷新行为：

  ```
  // Create a provider with custom refresh behavior.
  StsAssumeRoleCredentialsProvider customRefreshProvider = 
      StsAssumeRoleCredentialsProvider.builder()
          .refreshRequest(AssumeRoleRequest.builder()
              .roleArn("arn:aws:iam::123456789012:role/my-role")
              .roleSessionName("custom-session")
              .build())
          .stsClient(StsClient.create())
          .asyncCredentialUpdateEnabled(true) // Use a background thread to prefetch credentials.
          .build();
  
  S3Client s3Client = S3Client.builder()
      .credentialsProvider(customRefreshProvider)
      .build();
  ```