在 中指定特定的登入資料提供者 AWS SDK for Java 2.x - AWS SDK for Java 2.x

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

在 中指定特定的登入資料提供者 AWS SDK for Java 2.x

雖然預設登入資料提供者鏈結在許多案例中都很方便,但明確指定登入資料提供者可讓您更好地控制身分驗證行為、效能和安全性。

您可能想要指定登入資料提供者的原因可能包括:

  • 預設供應商鏈結會依序檢查多個來源,這會新增延遲:

    // 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();