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

如何让带Cognito授权的API Gateway仅上传文件至S3用户专属前缀目录?

实现API Gateway上传文件到S3用户专属目录的方案

方法一:利用API Gateway集成请求映射模板注入用户前缀

既然已经配置了Cognito授权器,API Gateway可以直接获取到用户的身份标识(比如用户名username或唯一IDsub),通过修改集成请求的路径或映射模板,自动给S3对象键加上用户专属前缀:

  • 进入API Gateway对应上传方法(如PUT/POST)的集成请求标签
  • 修改请求路径:将原S3路径(如your-bucket/{object-key})改为your-bucket/$context.authorizer.claims.username/{object-key},其中$context.authorizer.claims.username会自动替换为当前授权用户的用户名
  • 若使用表单上传(multipart/form-data),需在映射模板中编写VTL代码,解析表单并拼接用户前缀到文件名前,示例模板片段:
    #set($filename = $input.params('filename'))
    #set($key = "$context.authorizer.claims.username/$filename")
    {
      "key": "$key",
      "content": $input.body
    }
    
  • 给API Gateway的执行角色配置S3权限,允许其对arn:aws:s3:::your-bucket/${cognito-identity.amazonaws.com:sub}/*执行s3:PutObject操作

方法二:通过Lambda中间层处理路径拼接

如果映射模板配置复杂,可引入Lambda作为中转层,实现更灵活的路径控制:

  • 前端上传文件到API Gateway,触发Lambda函数
  • Lambda从event.requestContext.authorizer.claims中提取用户标识(如username或sub)
  • 拼接生成S3目标路径(如{username}/{原文件名}),调用S3的PutObject接口完成上传
  • 此方式可额外添加校验逻辑(如文件大小限制、文件名合规性检查)

方法三:配置S3桶策略限制用户访问范围

为防止越权上传,需配置S3桶策略确保用户只能操作自己的目录:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::你的AWS账号ID:role/API-Gateway执行角色ARN"
      },
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::your-bucket/${cognito-identity.amazonaws.com:sub}/*"
    },
    {
      "Effect": "Deny",
      "Principal": {
        "AWS": "arn:aws:iam::你的AWS账号ID:role/API-Gateway执行角色ARN"
      },
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::your-bucket/*",
      "Condition": {
        "StringNotLike": {
          "s3:prefix": "${cognito-identity.amazonaws.com:sub}/"
        }
      }
    }
  ]
}

可根据需求将${cognito-identity.amazonaws.com:sub}替换为${cognito-identity.amazonaws.com:username}。

注意事项

  • 确认Cognito授权器配置正确,API Gateway能正常获取用户的claims信息(可通过API Gateway测试功能查看上下文输出验证)
  • 映射模板需匹配请求的Content-Type(如multipart/form-data或application/json)
  • 测试时可通过API Gateway测试工具查看集成请求的最终S3路径是否正确拼接了用户前缀

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 06:05:19