本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
使用 Java 开发工具包 2.x 的 IAM 示例
以下代码示例向您展示了如何使用 with IAM 来执行操作和实现常见场景。AWS SDK for Java 2.x
操作是大型程序的代码摘录,必须在上下文中运行。虽然操作向您展示了如何调用单个服务函数,但您可以在其相关场景和跨服务示例中查看操作的上下文。
场景是展示如何通过在同一服务中调用多个函数来完成特定任务的代码示例。
每个示例都包含一个链接GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。
操作
以下代码示例显示了如何将 IAM 策略附加到角色。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn ) { try { ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder() .roleName(roleName) .build(); ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request); List<AttachedPolicy> attachedPolicies = response.attachedPolicies(); // Ensure that the policy is not attached to this role String polArn = ""; for (AttachedPolicy policy: attachedPolicies) { polArn = policy.policyArn(); if (polArn.compareTo(policyArn)==0) { System.out.println(roleName + " policy is already attached to this role."); return; } } AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder() .roleName(roleName) .policyArn(policyArn) .build(); iam.attachRolePolicy(attachRequest); System.out.println("Successfully attached policy " + policyArn + " to role " + roleName); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } System.out.println("Done"); }
-
有关 API 的详细信息,请参阅 AttachRolePolicyAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何创建 IAM 策略。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static String createIAMPolicy(IamClient iam, String policyName ) { try { // Create an IamWaiter object. IamWaiter iamWaiter = iam.waiter(); CreatePolicyRequest request = CreatePolicyRequest.builder() .policyName(policyName) .policyDocument(PolicyDocument) .build(); CreatePolicyResponse response = iam.createPolicy(request); // Wait until the policy is created. GetPolicyRequest polRequest = GetPolicyRequest.builder() .policyArn(response.policy().arn()) .build(); WaiterResponse<GetPolicyResponse> waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest); waitUntilPolicyExists.matched().response().ifPresent(System.out::println); return response.policy().arn(); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return "" ; }
-
有关 API 的详细信息,请参阅 CreatePolicyAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何创建 IAM 角色。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static String createIAMRole(IamClient iam, String rolename, String fileLocation ) throws Exception { try { JSONObject jsonObject = (JSONObject) readJsonSimpleDemo(fileLocation); CreateRoleRequest request = CreateRoleRequest.builder() .roleName(rolename) .assumeRolePolicyDocument(jsonObject.toJSONString()) .description("Created using the AWS SDK for Java") .build(); CreateRoleResponse response = iam.createRole(request); System.out.println("The ARN of the role is "+response.role().arn()); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static Object readJsonSimpleDemo(String filename) throws Exception { FileReader reader = new FileReader(filename); JSONParser jsonParser = new JSONParser(); return jsonParser.parse(reader); }
-
有关 API 的详细信息,请参阅 CreateRoleAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何创建 IAM 用户。
警告
为了避免安全风险,在开发专用软件或处理真实数据时,请勿使用 IAM 用户进行身份验证。而是使用与身份提供商的联合身份验证,例如 AWS IAM Identity Center (successor to AWS Single Sign-On)。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static String createIAMUser(IamClient iam, String username ) { try { // Create an IamWaiter object IamWaiter iamWaiter = iam.waiter(); CreateUserRequest request = CreateUserRequest.builder() .userName(username) .build(); CreateUserResponse response = iam.createUser(request); // Wait until the user is created GetUserRequest userRequest = GetUserRequest.builder() .userName(response.user().userName()) .build(); WaiterResponse<GetUserResponse> waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest); waitUntilUserExists.matched().response().ifPresent(System.out::println); return response.user().userName(); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; }
-
有关 API 的详细信息,请参阅 CreateUserAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何创建 IAM 访问密钥。
警告
为了避免安全风险,在开发专用软件或处理真实数据时,请勿使用 IAM 用户进行身份验证。而是使用与身份提供商的联合身份验证,例如 AWS IAM Identity Center (successor to AWS Single Sign-On)。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static String createIAMAccessKey(IamClient iam,String user) { try { CreateAccessKeyRequest request = CreateAccessKeyRequest.builder() .userName(user) .build(); CreateAccessKeyResponse response = iam.createAccessKey(request); return response.accessKey().accessKeyId(); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; }
-
有关 API 的详细信息,请参阅 CreateAccessKeyAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示如何为 IAM 账户创建别名。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void createIAMAccountAlias(IamClient iam, String alias) { try { CreateAccountAliasRequest request = CreateAccountAliasRequest.builder() .accountAlias(alias) .build(); iam.createAccountAlias(request); System.out.println("Successfully created account alias: " + alias); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 CreateAccountAliasAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何删除 IAM 策略。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void deleteIAMPolicy(IamClient iam,String policyARN) { try { DeletePolicyRequest request = DeletePolicyRequest.builder() .policyArn(policyARN) .build(); iam.deletePolicy(request); System.out.println("Successfully deleted the policy"); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } System.out.println("Done"); }
-
有关 API 的详细信息,请参阅 DeletePolicyAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何删除 IAM 用户。
警告
为了避免安全风险,在开发专用软件或处理真实数据时,请勿使用 IAM 用户进行身份验证。而是使用与身份提供商的联合身份验证,例如 AWS IAM Identity Center (successor to AWS Single Sign-On)。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void deleteIAMUser(IamClient iam, String userName) { try { DeleteUserRequest request = DeleteUserRequest.builder() .userName(userName) .build(); iam.deleteUser(request); System.out.println("Successfully deleted IAM user " + userName); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 DeleteUserAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何删除 IAM 访问密钥。
警告
为了避免安全风险,在开发专用软件或处理真实数据时,请勿使用 IAM 用户进行身份验证。而是使用与身份提供商的联合身份验证,例如 AWS IAM Identity Center (successor to AWS Single Sign-On)。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void deleteKey(IamClient iam ,String username, String accessKey ) { try { DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder() .accessKeyId(accessKey) .userName(username) .build(); iam.deleteAccessKey(request); System.out.println("Successfully deleted access key " + accessKey + " from user " + username); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 DeleteAccessKeyAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何删除 IAM 账户别名。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void deleteIAMAccountAlias(IamClient iam, String alias ) { try { DeleteAccountAliasRequest request = DeleteAccountAliasRequest.builder() .accountAlias(alias) .build(); iam.deleteAccountAlias(request); System.out.println("Successfully deleted account alias " + alias); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } System.out.println("Done"); }
-
有关 API 的详细信息,请参阅 DeleteAccountAliasAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何将 IAM 策略与角色分离。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void detachPolicy(IamClient iam, String roleName, String policyArn ) { try { DetachRolePolicyRequest request = DetachRolePolicyRequest.builder() .roleName(roleName) .policyArn(policyArn) .build(); iam.detachRolePolicy(request); System.out.println("Successfully detached policy " + policyArn + " from role " + roleName); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 DetachRolePolicyAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示如何列出用户的 IAM 访问密钥。
警告
为了避免安全风险,在开发专用软件或处理真实数据时,请勿使用 IAM 用户进行身份验证。而是使用与身份提供商的联合身份验证,例如 AWS IAM Identity Center (successor to AWS Single Sign-On)。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void listKeys( IamClient iam,String userName ){ try { boolean done = false; String newMarker = null; while (!done) { ListAccessKeysResponse response; if(newMarker == null) { ListAccessKeysRequest request = ListAccessKeysRequest.builder() .userName(userName) .build(); response = iam.listAccessKeys(request); } else { ListAccessKeysRequest request = ListAccessKeysRequest.builder() .userName(userName) .marker(newMarker) .build(); response = iam.listAccessKeys(request); } for (AccessKeyMetadata metadata : response.accessKeyMetadata()) { System.out.format("Retrieved access key %s", metadata.accessKeyId()); } if (!response.isTruncated()) { done = true; } else { newMarker = response.marker(); } } } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 ListAccessKeysAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何列出 IAM 账户别名。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void listAliases(IamClient iam) { try { ListAccountAliasesResponse response = iam.listAccountAliases(); for (String alias : response.accountAliases()) { System.out.printf("Retrieved account alias %s", alias); } } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 ListAccountAliasesAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何列出 IAM 用户。
警告
为了避免安全风险,在开发专用软件或处理真实数据时,请勿使用 IAM 用户进行身份验证。而是使用与身份提供商的联合身份验证,例如 AWS IAM Identity Center (successor to AWS Single Sign-On)。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void listAllUsers(IamClient iam ) { try { boolean done = false; String newMarker = null; while(!done) { ListUsersResponse response; if (newMarker == null) { ListUsersRequest request = ListUsersRequest.builder().build(); response = iam.listUsers(request); } else { ListUsersRequest request = ListUsersRequest.builder() .marker(newMarker) .build(); response = iam.listUsers(request); } for(User user : response.users()) { System.out.format("\n Retrieved user %s", user.userName()); AttachedPermissionsBoundary permissionsBoundary = user.permissionsBoundary(); if (permissionsBoundary != null) System.out.format("\n Permissions boundary details %s", permissionsBoundary.permissionsBoundaryTypeAsString()); } if(!response.isTruncated()) { done = true; } else { newMarker = response.marker(); } } } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 ListUsersAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何更新 IAM 用户。
警告
为了避免安全风险,在开发专用软件或处理真实数据时,请勿使用 IAM 用户进行身份验证。而是使用与身份提供商的联合身份验证,例如 AWS IAM Identity Center (successor to AWS Single Sign-On)。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void updateIAMUser(IamClient iam, String curName,String newName ) { try { UpdateUserRequest request = UpdateUserRequest.builder() .userName(curName) .newUserName(newName) .build(); iam.updateUser(request); System.out.printf("Successfully updated user to username %s", newName); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 UpdateUserAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何更新 IAM 访问密钥。
警告
为了避免安全风险,在开发专用软件或处理真实数据时,请勿使用 IAM 用户进行身份验证。而是使用与身份提供商的联合身份验证,例如 AWS IAM Identity Center (successor to AWS Single Sign-On)。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void updateKey(IamClient iam, String username, String accessId, String status ) { try { if (status.toLowerCase().equalsIgnoreCase("active")) { statusType = StatusType.ACTIVE; } else if (status.toLowerCase().equalsIgnoreCase("inactive")) { statusType = StatusType.INACTIVE; } else { statusType = StatusType.UNKNOWN_TO_SDK_VERSION; } UpdateAccessKeyRequest request = UpdateAccessKeyRequest.builder() .accessKeyId(accessId) .userName(username) .status(statusType) .build(); iam.updateAccessKey(request); System.out.printf("Successfully updated the status of access key %s to" + "status %s for user %s", accessId, status, username); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 UpdateAccessKeyAWS SDK for Java 2.xAPI 参考文档。
-
场景
以下代码示例显示了如何创建用户和代入角色。
警告
为了避免安全风险,在开发专用软件或处理真实数据时,请勿使用 IAM 用户进行身份验证。而是使用与身份提供商的联合身份验证,例如 AWS IAM Identity Center (successor to AWS Single Sign-On)。
创建没有权限的用户。
创建授予列出账户的 Amazon S3 存储桶的权限的角色
添加策略以允许用户代入该角色。
代入角色并使用临时凭证列出 S3 存储桶,然后清除资源。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 创建包装 IAM 用户操作的函数。
/* To run this Java V2 code example, set up your development environment, including your credentials. For information, see this documentation topic: https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html This example performs these operations: 1. Creates a user that has no permissions. 2. Creates a role and policy that grants Amazon S3 permissions. 3. Creates a role. 4. Grants the user permissions. 5. Gets temporary credentials by assuming the role. Creates an Amazon S3 Service client object with the temporary credentials. 6. Deletes the resources. */ public class IAMScenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); public static final String PolicyDocument = "{" + " \"Version\": \"2012-10-17\"," + " \"Statement\": [" + " {" + " \"Effect\": \"Allow\"," + " \"Action\": [" + " \"s3:*\"" + " ]," + " \"Resource\": \"*\"" + " }" + " ]" + "}"; public static String userArn; public static void main(String[] args) throws Exception { final String usage = "\n" + "Usage:\n" + " <username> <policyName> <roleName> <roleSessionName> <bucketName> \n\n" + "Where:\n" + " username - The name of the IAM user to create. \n\n" + " policyName - The name of the policy to create. \n\n" + " roleName - The name of the role to create. \n\n" + " roleSessionName - The name of the session required for the assumeRole operation. \n\n" + " bucketName - The name of the Amazon S3 bucket from which objects are read. \n\n"; if (args.length != 5) { System.out.println(usage); System.exit(1); } String userName = args[0]; String policyName = args[1]; String roleName = args[2]; String roleSessionName = args[3]; String bucketName = args[4]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .credentialsProvider(ProfileCredentialsProvider.create()) .build(); System.out.println(DASHES); System.out.println("Welcome to the AWS IAM example scenario."); System.out.println(DASHES); System.out.println(DASHES); System.out.println(" 1. Create the IAM user."); User createUser = createIAMUser(iam, userName); System.out.println(DASHES); userArn = createUser.arn(); AccessKey myKey = createIAMAccessKey(iam, userName); String accessKey = myKey.accessKeyId(); String secretKey = myKey.secretAccessKey(); String assumeRolePolicyDocument = "{" + "\"Version\": \"2012-10-17\"," + "\"Statement\": [{" + "\"Effect\": \"Allow\"," + "\"Principal\": {" + " \"AWS\": \"" + userArn + "\"" + "}," + "\"Action\": \"sts:AssumeRole\"" + "}]" + "}"; System.out.println(assumeRolePolicyDocument); System.out.println(userName + " was successfully created."); System.out.println(DASHES); System.out.println("2. Creates a policy."); String polArn = createIAMPolicy(iam, policyName); System.out.println("The policy " + polArn + " was successfully created."); System.out.println(DASHES); System.out.println(DASHES); System.out.println("3. Creates a role."); TimeUnit.SECONDS.sleep(30); String roleArn = createIAMRole(iam, roleName, assumeRolePolicyDocument); System.out.println(roleArn + " was successfully created."); System.out.println(DASHES); System.out.println(DASHES); System.out.println("4. Grants the user permissions."); attachIAMRolePolicy(iam, roleName, polArn); System.out.println(DASHES); System.out.println(DASHES); System.out.println("*** Wait for 30 secs so the resource is available"); TimeUnit.SECONDS.sleep(30); System.out.println("5. Gets temporary credentials by assuming the role."); System.out.println("Perform an Amazon S3 Service operation using the temporary credentials."); assumeRole(roleArn, roleSessionName, bucketName, accessKey, secretKey); System.out.println(DASHES); System.out.println(DASHES); System.out.println("6 Getting ready to delete the AWS resources"); deleteKey(iam, userName, accessKey ); deleteRole(iam, roleName, polArn); deleteIAMUser(iam, userName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("This IAM Scenario has successfully completed"); System.out.println(DASHES); } public static AccessKey createIAMAccessKey(IamClient iam, String user) { try { CreateAccessKeyRequest request = CreateAccessKeyRequest.builder() .userName(user) .build(); CreateAccessKeyResponse response = iam.createAccessKey(request); return response.accessKey(); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; } public static User createIAMUser(IamClient iam, String username) { try { // Create an IamWaiter object IamWaiter iamWaiter = iam.waiter(); CreateUserRequest request = CreateUserRequest.builder() .userName(username) .build(); // Wait until the user is created. CreateUserResponse response = iam.createUser(request); GetUserRequest userRequest = GetUserRequest.builder() .userName(response.user().userName()) .build(); WaiterResponse<GetUserResponse> waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest); waitUntilUserExists.matched().response().ifPresent(System.out::println); return response.user(); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; } public static String createIAMRole(IamClient iam, String rolename, String json) { try { CreateRoleRequest request = CreateRoleRequest.builder() .roleName(rolename) .assumeRolePolicyDocument(json) .description("Created using the AWS SDK for Java") .build(); CreateRoleResponse response = iam.createRole(request); System.out.println("The ARN of the role is " + response.role().arn()); return response.role().arn(); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static String createIAMPolicy(IamClient iam, String policyName) { try { // Create an IamWaiter object. IamWaiter iamWaiter = iam.waiter(); CreatePolicyRequest request = CreatePolicyRequest.builder() .policyName(policyName) .policyDocument(PolicyDocument).build(); CreatePolicyResponse response = iam.createPolicy(request); GetPolicyRequest polRequest = GetPolicyRequest.builder() .policyArn(response.policy().arn()) .build(); WaiterResponse<GetPolicyResponse> waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest); waitUntilPolicyExists.matched().response().ifPresent(System.out::println); return response.policy().arn(); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn) { try { ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder() .roleName(roleName) .build(); ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request); List<AttachedPolicy> attachedPolicies = response.attachedPolicies(); String polArn; for (AttachedPolicy policy : attachedPolicies) { polArn = policy.policyArn(); if (polArn.compareTo(policyArn) == 0) { System.out.println(roleName + " policy is already attached to this role."); return; } } AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder() .roleName(roleName) .policyArn(policyArn) .build(); iam.attachRolePolicy(attachRequest); System.out.println("Successfully attached policy " + policyArn + " to role " + roleName); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } // Invoke an Amazon S3 operation using the Assumed Role. public static void assumeRole(String roleArn, String roleSessionName, String bucketName, String keyVal, String keySecret) { // Use the creds of the new IAM user that was created in this code example. AwsBasicCredentials credentials = AwsBasicCredentials.create(keyVal, keySecret); StsClient stsClient = StsClient.builder() .region(Region.US_EAST_1) .credentialsProvider(StaticCredentialsProvider.create(credentials)) .build(); try { AssumeRoleRequest roleRequest = AssumeRoleRequest.builder() .roleArn(roleArn) .roleSessionName(roleSessionName) .build(); AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest); Credentials myCreds = roleResponse.credentials(); String key = myCreds.accessKeyId(); String secKey = myCreds.secretAccessKey(); String secToken = myCreds.sessionToken(); // List all objects in an Amazon S3 bucket using the temp creds 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(); System.out.println("Created a S3Client using temp credentials."); System.out.println("Listing objects in " + bucketName); ListObjectsRequest listObjects = ListObjectsRequest.builder() .bucket(bucketName) .build(); ListObjectsResponse res = s3.listObjects(listObjects); List<S3Object> objects = res.contents(); for (S3Object myValue : objects) { System.out.println("The name of the key is " + myValue.key()); System.out.println("The owner is " + myValue.owner()); } } catch (StsException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void deleteRole(IamClient iam, String roleName, String polArn) { try { // First the policy needs to be detached. DetachRolePolicyRequest rolePolicyRequest = DetachRolePolicyRequest.builder() .policyArn(polArn) .roleName(roleName) .build(); iam.detachRolePolicy(rolePolicyRequest); // Delete the policy. DeletePolicyRequest request = DeletePolicyRequest.builder() .policyArn(polArn) .build(); iam.deletePolicy(request); System.out.println("*** Successfully deleted " + polArn); // Delete the role. DeleteRoleRequest roleRequest = DeleteRoleRequest.builder() .roleName(roleName) .build(); iam.deleteRole(roleRequest); System.out.println("*** Successfully deleted " + roleName); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void deleteKey(IamClient iam ,String username, String accessKey ) { try { DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder() .accessKeyId(accessKey) .userName(username) .build(); iam.deleteAccessKey(request); System.out.println("Successfully deleted access key " + accessKey + " from user " + username); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void deleteIAMUser(IamClient iam, String userName) { try { DeleteUserRequest request = DeleteUserRequest.builder() .userName(userName) .build(); iam.deleteUser(request); System.out.println("*** Successfully deleted " + userName); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
-
有关 API 详细信息,请参阅《AWS SDK for Java 2.x API 参考》中的以下主题。
-