Amplify Storage API无法访问受保护文件:Storage.put未返回完整Key问题
问题:Protected级别上传文件后管理员无法访问,Storage.put不返回完整Key
将用户以protected级别上传文件后,管理员无法访问该文件。原因是aws-amplify会在存储路径中添加用户AWS区域和用户Cognito身份ID作为前缀,但Storage.put仅返回文件名作为key。目前需手动存储用户AWS区域和Cognito身份ID,访问文件时还要判断登录用户是管理员还是所有者,若非所有者则需添加前缀,使用Storage.get时也存在此困扰。
上传代码示例
import { Storage } from 'aws-amplify' const result = Storage.put('file.pdf', file, { level: 'protected', contentType: 'application/pdf' }) // result: // { key: 'file.pdf' } // path in aws bucket: // {user-aws-region}:{user-cognito-identity-id}/file.pdf
为什么Storage.put不返回完整Key?
Amplify的Storage模块设计时,protected级别的文件路径前缀是自动处理的——它默认帮用户隐藏了身份相关的前缀细节,让开发者可以用更简洁的逻辑处理文件上传(不用手动拼接前缀)。这种设计的核心是让文件操作对普通用户更透明:普通用户只需要关心自己的文件名,不需要了解底层的身份前缀规则。
但这种设计确实给管理员跨用户访问文件带来了麻烦,因为管理员需要知道完整的存储路径才能访问其他用户的protected文件。
解决方法
获取完整存储路径
你可以通过身份信息手动构造完整路径,再用于访问:import { Auth, Storage } from 'aws-amplify'; // 管理员需获取目标用户的identityId和区域 const targetUserIdentityId = "目标用户的Cognito身份ID"; const region = Auth.configure().region; const fileName = "file.pdf"; // 构造完整的protected路径 const fullKey = `${region}:${targetUserIdentityId}/${fileName}`; // 管理员访问目标用户的文件 const fileUrl = await Storage.get(fullKey, { level: 'protected' });上传时记录完整Key
上传前手动拼接前缀,这样Storage.put会返回完整路径:import { Auth, Storage } from 'aws-amplify'; const user = await Auth.currentAuthenticatedUser(); const identityId = user.attributes.sub; const region = Auth.configure().region; const fileName = 'file.pdf'; const fullKey = `${region}:${identityId}/${fileName}`; const result = await Storage.put(fullKey, file, { level: 'protected', contentType: 'application/pdf' }); // 此时result.key为完整路径:{user-aws-region}:{user-cognito-identity-id}/file.pdf调整IAM策略简化访问
修改S3的IAM策略,允许管理员绕过前缀限制直接访问所有用户的同名文件:{ "Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::你的存储桶名称/*"], "Condition": { "StringLike": { "s3:prefix": ["*:*/file.pdf"] } } }之后管理员使用
Storage.get('file.pdf', { level: 'protected' })即可自动匹配所有用户的文件路径。
内容的提问来源于stack exchange,提问作者conor909
相关产品推荐
相关产品推荐

