Amazon S3 Bucket Policy不生效:如何仅允许单个Cognito用户访问?
问题分析与解决方案
你的问题核心是条件键选择错误:aws:PrincipalTag/CognitoIdentityId仅适用于带有标签的IAM用户/角色,并不适用于Cognito身份池的用户。Cognito用户通过临时凭证访问S3时,其身份标识不会以PrincipalTag形式出现在请求上下文里,所以原策略的条件永远匹配失败。
正确配置方式
要限制单个Cognito身份访问S3,应使用aws:userId条件键。Cognito认证用户的临时凭证对应的userId格式为:cognito-identity.amazonaws.com:你的IdentityID,以此作为匹配值即可。
修正后的Bucket Policy
{ "Version": "2012-10-17", "Statement": [ { "Sid": "AllowCognitoUserObjectAccess", "Effect": "Allow", "Principal": "*", "Action": ["s3:PutObject", "s3:GetObject"], "Resource": "arn:aws:s3:::testbucketoz123/*", "Condition": { "StringEquals": { "aws:userId": "cognito-identity.amazonaws.com:099702b2-0c2e-42ce-8e27-3012ab6032ad" } } }, { "Sid": "AllowCognitoUserListBucket", "Resource": "arn:aws:s3:::testbucketoz123", "Effect": "Allow", "Principal": "*", "Action": ["s3:ListBucket"], "Condition": { "StringEquals": { "aws:userId": "cognito-identity.amazonaws.com:099702b2-0c2e-42ce-8e27-3012ab6032ad" } } } ] }
额外注意事项
- 原策略中两个
Statement的Sid重复,会导致策略解析异常,修正后已改为不同标识。 - 若你的Cognito用户通过用户池关联身份池,也可通过
aws:PrincipalArn匹配用户对应的角色ARN,但aws:userId的方式更直接匹配Identity ID的需求。
内容的提问来源于stack exchange,提问作者AliOz
相关产品推荐
相关产品推荐

