NodeJS中AWS createPresignedPost上传文件时出现凭证缺失错误
问题分析与解决方案
错误原因
你直接将异步函数getCognitoCredentials本身传给了S3Client的credentials参数,但AWS SDK无法直接处理这种未执行的异步函数,导致在尝试生成预签名POST时无法获取有效凭证,抛出Credential is missing错误。
修复方案
方案一:先获取凭证再创建S3Client(推荐)
在异步环境中先等待凭证获取完成,再初始化S3Client,确保凭证就绪后再执行后续操作:
export async function getCognitoCredentials() { const stsClient = new STSClient({ region: 'eu-west-1' }) const assumeRoleCommand = new AssumeRoleCommand({ RoleArn: `arn:aws:iam::${id}:role/new-iam-cross-account-role`, RoleSessionName: 'serviceName', DurationSeconds: 3600, }) const assumeRoleResponse = await stsClient.send(assumeRoleCommand) if (!assumeRoleResponse.Credentials) { throw new Error('STS未返回有效凭证'); } return { accessKeyId: assumeRoleResponse.Credentials.AccessKeyId, secretAccessKey: assumeRoleResponse.Credentials.SecretAccessKey, sessionToken: assumeRoleResponse.Credentials.SessionToken, } } // 封装到异步函数中执行 async function generatePresignedPost() { // 先获取凭证 const credentials = await getCognitoCredentials(); const s3Client = new S3Client({ region: 'eu-west-1', credentials }); console.log(s3Client) const { url, fields } = await createPresignedPost(s3Client, { Bucket: 'bucketName', Key: path, Conditions: [ ['content-length-range', min, max], ['starts-with', '$Content-Type', 'image/'], ], Expires: 600, }) console.log('url >>>', url) console.log('fields >>>', fields) } // 调用执行 generatePresignedPost();
方案二:使用凭证提供者模式(懒加载)
如果需要S3Client在需要时自动获取凭证,可以将credentials设为一个返回Promise的函数:
const s3Client = new S3Client({ region: 'eu-west-1', credentials: async () => await getCognitoCredentials() }) // 后续代码保持不变 async function generatePresignedPost() { console.log(s3Client) const { url, fields } = await createPresignedPost(s3Client, { Bucket: 'bucketName', Key: path, Conditions: [ ['content-length-range', min, max], ['starts-with', '$Content-Type', 'image/'], ], Expires: 600, }) console.log('url >>>', url) console.log('fields >>>', fields) } generatePresignedPost();
额外检查项
- 确认
id变量已正确赋值,RoleArn中的AWS账号ID无误 - 确保初始化STSClient的基础凭证拥有
sts:AssumeRole权限 - 建议在
getCognitoCredentials中添加错误捕获,避免因STS调用失败导致的静默错误
内容的提问来源于stack exchange,提问作者Onur
相关产品推荐
相关产品推荐

