如何使用Node / Typescript获取已签名的S3网址?

时间:2017-12-22 11:38:25

标签: javascript typescript amazon-s3 graphcool

在FaaS中使用Node + aws-sdk,我正在尝试使用预先指定的URL将文件上传到S3存储桶。当我上传文件时,我得到以下回复

InvalidAccessKeyId您提供的AWS访问密钥ID不存在于我们的记录中。

// getUploadUrl
import { FunctionEvent } from 'graphcool-lib'
import * as AWS from 'aws-sdk'

const BUCKET = process.env['BUCKET'];
const AWS_ACCESS_KEY_ID = process.env['AWS_ACCESS_KEY_ID'];
const AWS_SECRET_ACCESS_KEY = process.env['AWS_SECRET_ACCESS_KEY'];

const signedUrlExpiresSeconds = 60*10;

AWS.config.update({
  accessKeyId: AWS_ACCESS_KEY_ID,
  secretAccessKey: AWS_SECRET_ACCESS_KEY,
  region: 'eu-west-2'
});

const s3 = new AWS.S3({ apiVersion: "2006-03-01" })

interface EventData {
  fileName: string
}

export default async (event: FunctionEvent<EventData>) => {

  if (!event.context.auth || !event.context.auth.nodeId) {
    return { error: 'No user logged in.' }
  }

  try {
    const { fileName } = event.data;

    // Pre-signing a putObject (asynchronously)
    const params = { Bucket: BUCKET, Key: fileName, Expires: signedUrlExpiresSeconds }
    const uploadUrl: string = await s3.getSignedUrl('putObject', params)

    if (!uploadUrl) {
      return { error: 'Unable to get presigned upload URL from S3' }
    }



    return { data: { uploadUrl } }
  } catch (e) {
    console.log(e)
    return { error: 'An unexpected error occured during password change.' }
  }
}

以下是我对AWS IAM的权限

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::bucket-name/*"
        }
    ]
}

我正在使用以下内容上传文件

curl -v -T test.pdf presignedUrl

有什么想法吗?

这是生成的路径

"https://my-aws-s3-domain.s3.eu-west-2.amazonaws.com/test.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=XXXXXXX1222%2Feu-west-2%2Fs3%2Faws4_request&X-Amz-Date=20171222T153846Z&X-Amz-Expires=600&X-Amz-Signature=XXXXXX-268d&X-Amz-SignedHeaders=host"

我将AWS配置更新为AWS.config.update({ region: 'eu-west-2' });,因为它会自动从process.ENV中获取AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY(正如迈克尔所指出的那样)。

我再次尝试了,我收到Access denied响应,因此我将IAM政策更改为:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::my-s3-bucket-name"
        }
    ]
}

并且它仍然提供拒绝访问错误。

1 个答案:

答案 0 :(得分:1)

原来在Graphcool的环境变量中存在一个错误,这意味着AWS密钥没有更新。

可能与此问题有关: https://github.com/graphcool/framework/issues/799

编辑 - 在Graphcool中,AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY是受保护的环境变量。所以你不能使用它们