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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 06:30:25