[英]How to create aws role with permission using java sdk?
我正在嘗試創建具有特定權限的角色但沒有成功:
這是我的許可:
String jsonRole = "{" +
" \"Version\": \"2012-10-17\"," +
" \"Statement\": [" +
" {" +
" \"Effect\": \"Allow\"," +
" \"Action\": [" +
" \"s3:PutObject\"," +
" \"s3:GetObject\"," +
" \"s3:GetObjectVersion\"," +
" \"s3:DeleteObject\"," +
" \"s3:DeleteObjectVersion\"" +
" ]," +
" \"Resource\": \"arn:aws:s3:::"+artifactsBucket+"/"+company.getCompanyId()+"/*\"" +
" }" +
" ]" +
"}";
以及創建角色的命令:
AmazonIdentityManagement client = AmazonIdentityManagementClientBuilder.standard().build();
CreateRoleRequest request = new CreateRoleRequest().withPath("/companies-bucket-roles/").withRoleName(company.getName()+"-"+consoleUser.getConsoleUserId());
但我不知道如何為角色添加權限。 我在文檔中一無所獲。 任何想法?
提前致謝
如果要創建角色並添加策略,這是完整的代碼:
String jsonPolicyDocument = "{" +
" \"Version\": \"2012-10-17\"," +
" \"Statement\": [" +
" {" +
" \"Effect\": \"Allow\"," +
" \"Action\": [" +
" \"s3:PutObject\"," +
" \"s3:GetObject\"," +
" \"s3:GetObjectVersion\"," +
" \"s3:DeleteObject\"," +
" \"s3:DeleteObjectVersion\"" +
" ]," +
" \"Resource\": \"arn:aws:s3:::"+artifactsBucket+"/"+company.getCompanyId()+"/*\"" +
" }" +
" ]" +
"}";
String assumeRolePolicyDocument = "{" +
" \"Version\": \"2012-10-17\"," +
" \"Statement\": [" +
" {" +
" \"Effect\": \"Allow\"," +
" \"Principal\": {" +
" \"Federated\": \"cognito-identity.amazonaws.com\"" +
" }," +
" \"Action\": \"sts:AssumeRoleWithWebIdentity\"," +
" \"Condition\": {" +
" \"StringEquals\": {" +
" \"cognito-identity.amazonaws.com:aud\": \""+poolId+"\"" +
" }," +
" \"ForAnyValue:StringLike\": {" +
" \"cognito-identity.amazonaws.com:amr\": \"authenticated\"" +
" }" +
" }" +
" }" +
" ]" +
"}";
AmazonIdentityManagement client = AmazonIdentityManagementClientBuilder.standard().build();
// First create a policy
CreatePolicyRequest policyRequest = new CreatePolicyRequest()
.withPolicyName("company_" + company.getCompanyId() + "_s3bucket" + "_policy")
.withPolicyDocument(jsonPolicyDocument)
.withDescription("Policy created for the company "+company.getCompanyId()+". This policy give access to S3 bucket for this company");
CreatePolicyResult policyResponse = client.createPolicy(policyRequest);
String roleName = "company_" + company.getCompanyId() + "_role";
CreateRoleRequest request = new CreateRoleRequest()
.withPath("/"+rolesFolder+"/")
.withRoleName(roleName)
.withAssumeRolePolicyDocument(assumeRolePolicyDocument)
.withDescription("Role created for the company "+company.getCompanyId()+". This Role has for example policy for S3 bucket");
CreateRoleResult response = client.createRole(request);
// Attach the policy to the role
AttachRolePolicyRequest attachRequest = new AttachRolePolicyRequest()
.withRoleName(roleName)
.withPolicyArn(policyResponse.getPolicy().getArn());
AttachRolePolicyResult attachRolePolicyResult = client.attachRolePolicy(attachRequest);
logger.info(attachRolePolicyResult);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.