使用 AWS Cognito 和 IAM 角色访问 S3 的解决方案可以分为以下几个步骤:
import boto3
# 创建用户池
cognito_client = boto3.client('cognito-idp')
user_pool_response = cognito_client.create_user_pool(
PoolName='my-user-pool',
AdminCreateUserConfig={
'AllowAdminCreateUserOnly': True
}
)
# 创建身份池
identity_client = boto3.client('cognito-identity')
identity_pool_response = identity_client.create_identity_pool(
IdentityPoolName='my-identity-pool',
CognitoIdentityProviders=[
{
'ClientId': 'your-cognito-app-client-id',
'ProviderName': 'cognito-idp..amazonaws.com/',
'ServerSideTokenCheck': True
},
]
)
import json
import boto3
# 创建 IAM 角色
iam_client = boto3.client('iam')
role_response = iam_client.create_role(
RoleName='my-s3-role',
AssumeRolePolicyDocument=json.dumps({
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"Federated": "cognito-identity.amazonaws.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"cognito-identity.amazonaws.com:aud": identity_pool_response['IdentityPoolId']
}
}
}]
})
)
# 为角色授权 S3 访问权限
s3_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::my-bucket"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::my-bucket/*"
]
}
]
}
iam_client.put_role_policy(
RoleName='my-s3-role',
PolicyName='s3-access-policy',
PolicyDocument=json.dumps(s3_policy)
)
# 将角色与身份池关联
identity_client.set_identity_pool_roles(
IdentityPoolId=identity_pool_response['IdentityPoolId'],
Roles={
'authenticated': role_response['Role']['Arn']
}
)
import boto3
# 创建一个 Cognito 用户
cognito_user = cognito_client.admin_create_user(
UserPoolId=user_pool_response['UserPool']['Id'],
Username='my-cognito-user',
UserAttributes=[
{
'Name': 'email',
'Value': 'test@example.com'
},
],
TemporaryPassword='temporary-password',
MessageAction='SUPPRESS'
)
# 确认用户
cognito_client.admin_confirm_sign_up(
UserPoolId=user_pool_response['UserPool']['Id'],
Username='my-cognito-user'
)
# 获取用户的身份池凭证
identity_credentials = identity_client.get_id(
IdentityPoolId=identity_pool_response['IdentityPoolId'],
Logins={
'cognito-idp..amazonaws.com/': cognito_user['User']['Username']
}
)
# 使用身份池凭证访问 S3
s3_client = boto3.client('s3')
s3_client.list_buckets()
这些示例代码演示了如何使用 AWS SDK for Python (Boto3) 创建 AWS Cognito 用户池和身份池,然后创建一个 IAM 角色,为该角色授权访问 S3 的权限,并将角色与身份池关联。最后,我们创建了一个 Cognito 用户并获取了该用户的身份池凭证,然后使用凭证访问 S3。请根据你自己的具体情况修改代码中的参数和资源名称。