如何使用IAM角色在C#中访问S3

时间:2019-11-07 11:04:02

标签: c# amazon-s3 amazon-iam roles

当我尝试使用IAM角色访问C#中的S3时遇到了一个问题。以下是我已完成的步骤。

  1. 创建STS AssumeRole策略: { “ Version”:“ 2012-10-17”, “声明”:[     {         “ Sid”:“ VisualEditor0”,         “效果”:“允许”,         “ Action”:“ sts:AssumeRole”,         “ Resource”:“ arn:aws:iam :: 761612772509:role / S3TestRole”,         “条件”:{             “ StringEquals”:{                 “ aws:RequestedRegion”:“ ap-northeast-1”             }         }     } ] }

  2. 创建一个IAM角色(AWS其他帐户),并将AssumeRole策略附加到该角色: 角色ARN:arn:aws:iam :: 761612772509:role / S3TestRole 信任关系如图所示: enter image description here enter image description here

  3. 活动STS区域: enter image description here

  4. S3存储桶策略: { “ Id”:“ Policy1573183227944”, “ Version”:“ 2012-10-17”, “声明”:[     {         “ Sid”:“ Stmt1573183224129”,         “ Action”:“ s3:”,         “效果”:“允许”,         “资源”:[             “ arn:aws:s3 ::: 20190830s3bucket”,             “ arn:aws:s3 ::: 20190830s3bucket / ”         ],         “校长”:{             “ AWS”:[                 “ arn:aws:iam :: 761612772509:role / S3TestRole”             ]         }     } ] }


   try
            {
                AssumeRoleRequest assumeRequest = new AssumeRoleRequest
                {
                    RoleArn = "arn:aws:iam::761612772509:role/S3TestRole",
                    DurationSeconds = 3600,
                    Policy = "{\"Version\": \"2012-10-17\",\"Statement\": [{\"Sid\": \"VisualEditor0\",\"Effect\": \"Allow\",\"Action\": \"sts:AssumeRole\",\"Resource\": \"arn:aws:iam::761612772509:role/S3TestRole\",\"Condition\": {\"StringEquals\": {\"aws:RequestedRegion\": \"ap-northeast-1\"}}}]}",
                };


                AssumeRoleResult assumeRoleResult = new AmazonSecurityTokenServiceClient(RegionEndpoint.APNortheast1).AssumeRole(assumeRequest);


                AWSCredentials tempCredentials = new SessionAWSCredentials(
                   assumeRoleResult.Credentials.AccessKeyId,
                   assumeRoleResult.Credentials.SecretAccessKey,
                   assumeRoleResult.Credentials.SessionToken);
                s3Client = new AmazonS3Client(tempCredentials);
            }
            catch (Exception ex)
            {
                throw ex;
            }


我的区域位于ap-northeast-1中,并且在执行authenticRoleResult方法时,我总是得到“请求中包含的安全令牌无效。”并且InnerException为“远程服务器返回错误:(403)禁止。”错误。我可以知道我的配置或代码出什么问题吗?提前感谢您的帮助!

0 个答案:

没有答案