You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Lambda中获取Cognito用户sub以写入Amplify专属S3路径?

解决方法

首先明确:Amplify Storage的private/${cognito-identity.amazonaws.com:sub}路径中,cognito-identity.amazonaws.com:sub指的是Cognito身份池(Identity Pool)的身份ID,而非用户池(User Pool)的用户sub。这大概率是你之前用用户池sub拼接路径不匹配的原因。

下面提供两种可靠的实现方式:

方式一:前端直接传递身份ID到Lambda

前端通过Amplify Auth可以直接获取当前用户的身份池ID,调用Lambda时将其作为参数传入,Lambda用这个值拼接路径即可。

前端代码示例(React)

import { Auth, API } from 'aws-amplify';

// 获取身份池ID并调用Lambda
async function triggerImageProcessing(imageFile) {
  const credentials = await Auth.currentCredentials();
  const cognitoIdentityId = credentials.identityId; // 这就是需要的cognito-identity.amazonaws.com:sub

  // 调用Lambda(假设你用Amplify API定义了Lambda触发的接口)
  await API.post('ImageProcessingAPI', '/process-image', {
    body: {
      imageFile: imageFile,
      cognitoIdentityId: cognitoIdentityId
    }
  });
}

Lambda代码示例(Python)

import boto3

s3 = boto3.resource('s3')
amplify_bucket_name = '你的Amplify存储桶名称'

def lambda_handler(event, context):
    # 从前端参数中获取身份ID
    cognito_identity_id = event['body']['cognitoIdentityId']
    user_private_path = f'private/{cognito_identity_id}/processed-image.jpg'

    # 写入Amplify Storage的用户专属路径
    bucket = s3.Bucket(amplify_bucket_name)
    bucket.upload_file('/tmp/processed-image.jpg', user_private_path)

    return {
        'statusCode': 200,
        'body': '文件已成功写入用户专属路径'
    }

方式二:Lambda从请求上下文自动获取身份ID

如果你的Lambda是通过Amplify API Gateway触发,且开启了Cognito身份池授权,那么Lambda的event对象中会自动包含用户的身份信息,无需前端额外传递。

Lambda代码示例(Python)

import boto3

s3 = boto3.resource('s3')
amplify_bucket_name = '你的Amplify存储桶名称'

def lambda_handler(event, context):
    # 从请求上下文获取身份池ID
    cognito_identity_id = event['requestContext']['identity']['cognitoIdentityId']
    user_private_path = f'private/{cognito_identity_id}/processed-image.jpg'

    # 写入Amplify Storage的用户专属路径
    bucket = s3.Bucket(amplify_bucket_name)
    bucket.upload_file('/tmp/processed-image.jpg', user_private_path)

    return {
        'statusCode': 200,
        'body': '文件已成功写入用户专属路径'
    }

关键权限配置

确保Lambda的IAM角色拥有Amplify存储桶的写入权限,在角色的权限策略中添加:

{
    "Effect": "Allow",
    "Action": [
        "s3:PutObject"
    ],
    "Resource": "arn:aws:s3:::你的Amplify存储桶名称/private/${cognito-identity.amazonaws.com:sub}/*"
}

内容的提问来源于stack exchange,提问作者Seraphim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 10:55:15