如何通过CDK为Cognito用户池用户赋予S3存储桶读取权限
问题描述
现有如下CDK定义的S3存储桶:
const documentsBucket = new s3.Bucket( this, "documents-bucket", { bucketName: "documents-bucket", } );
以及如下定义的Cognito用户池和客户端:
const userPool = new cognito.UserPool(this, "domain-userpool", { mfa: cognito.Mfa.OFF, removalPolicy: cdk.RemovalPolicy.DESTROY, signInAliases: { email: true, }, autoVerify: { email: true, }, selfSignUpEnabled: true, accountRecovery: cognito.AccountRecovery.EMAIL_ONLY, }); const userPoolClient = userPool.addClient( "domain-userpool-client", { disableOAuth: true, authFlows: { userPassword: true, }, supportedIdentityProviders: [ cognito.UserPoolClientIdentityProvider.COGNITO, ], accessTokenValidity: cdk.Duration.days(1), idTokenValidity: cdk.Duration.days(1), refreshTokenValidity: cdk.Duration.days(30), } );
已定义IAM策略语句,但不知如何关联到用户池,让用户池内的用户拥有该存储桶的读取权限:
const readAccess = new iam.PolicyStatement({ actions: ["s3:GetObject", "s3:ListBucket"], resources: [ documentsBucket.bucketArn, `${documentsBucket.bucketArn}/*`, ], });
请问具体该如何操作?
解决方案
要让Cognito用户池的用户获得S3存储桶的读取权限,有两种常用的实现方式,可根据你的业务场景选择:
方式一:通过Cognito身份池关联角色(推荐用于临时凭证场景)
如果用户需要通过身份池获取临时IAM凭证访问S3,按以下步骤操作:
- 创建Cognito身份池并关联现有用户池:
const identityPool = new cognito.CfnIdentityPool(this, "domain-identity-pool", { allowUnauthenticatedIdentities: false, cognitoIdentityProviders: [ { clientId: userPoolClient.userPoolClientId, providerName: userPool.userPoolProviderName, }, ], });
- 创建授权用户对应的IAM角色,并附加S3读取权限:
const authenticatedRole = new iam.Role(this, "authenticated-role", { assumedBy: new iam.FederatedPrincipal( "cognito-identity.amazonaws.com", { StringEquals: { "cognito-identity.amazonaws.com:aud": identityPool.ref }, "ForAnyValue:StringLike": { "cognito-identity.amazonaws.com:amr": "authenticated" }, }, "sts:AssumeRoleWithWebIdentity" ), }); // 将已定义的读取权限附加到角色 authenticatedRole.addToPolicy(readAccess);
- 将角色与身份池绑定:
new cognito.CfnIdentityPoolRoleAttachment(this, "identity-pool-role-attachment", { identityPoolId: identityPool.ref, roles: { authenticated: authenticatedRole.roleArn, }, });
方式二:直接为用户池/用户组附加策略(适用于直接凭证场景)
如果用户通过用户池API直接获取凭证,可直接将策略关联到用户池或用户组:
方案A:直接附加到用户池
- 先将策略语句打包成托管策略:
const s3ReadPolicy = new iam.ManagedPolicy(this, "s3-read-policy", { statements: [readAccess], });
- 将托管策略附加到用户池:
userPool.addManagedPolicy(s3ReadPolicy);
方案B:通过用户组实现权限细分
如果需要给不同用户分配不同权限,推荐创建用户组并绑定策略:
// 创建用户池组 const documentReadersGroup = new cognito.UserPoolGroup(this, "document-readers-group", { userPool: userPool, groupName: "document-readers", }); // 给组附加S3读取权限策略 documentReadersGroup.addManagedPolicy(s3ReadPolicy);
后续只需将用户添加到该组,就能自动获得对应权限。
内容的提问来源于stack exchange,提问作者Ciprian Tanana
相关产品推荐
相关产品推荐

