创建预签名 post 时,AWS SDK 不包括 X-Amz-Credential 中的访问密钥 (AKID),但仅限于 Heroku

AWS SDK not including Access Key (AKID) in X-Amz-Credential when creating presigned post, but only on Heroku

我正在直接上传到 S3,我有这样声明的预签名 post:

@s3_direct_post = S3_BUCKET.presigned_post(key: "images/#{SecureRandom.uuid}/${filename}", success_action_status: '201', acl: 'public-read', allow_any: ['utf8', 'authenticity_token'])

在开发环境中,它可以正确构建所有内容,我得到如下信息:

{"key"=>"images/1be59d13-9d65-4d70-b631-93834409f361/${filename}", "success_action_status"=>"201", "acl"=>"public-read", "policy"=>"<BASE_64_POLICY>", "x-amz-credential"=>"<MY_ACCESS_KEY>/20180505/us-east-1/s3/aws4_request", "x-amz-algorithm"=>"AWS4-HMAC-SHA256", "x-amz-date"=>"20180505T232823Z", "x-amz-signature"=>"<AMZ_SIGNATURE>"}

但是在我把它推送到 Heroku 之后,我得到了这样的东西:

{"key"=>"images/1be59d13-9d65-4d70-b631-93834409f361/${filename}", "success_action_status"=>"201", "acl"=>"public-read", "policy"=>"<BASE_64_POLICY>", "x-amz-credential"=>"/20180505/us-east-1/s3/aws4_request", "x-amz-algorithm"=>"AWS4-HMAC-SHA256", "x-amz-date"=>"20180505T232823Z", "x-amz-signature"=>"<AMZ_SIGNATURE>"}

现在我的访问密钥 (AKID) 已不存在,我收到此错误:

<Error><Code>InvalidArgument</Code><Message>a non-empty Access Key (AKID) must be provided in the credential.</Message><ArgumentName>X-Amz-Credential</ArgumentName><ArgumentValue>/20180505/us-east-1/s3/aws4_request</ArgumentValue><RequestId>%REQUESTID%</RequestId><HostId>%HOSTID%</HostId></Error>

我的 AWS 凭证在 initalizers/aws.rb 中声明,因此它们不依赖于环境类型。可能是什么原因造成的?

编辑(显示我如何声明 S3_BUCKET 是我在 aws.rb 中初始化的常量):

Aws.config.update({ region: 'us-east-1', credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']) })

S3_BUCKET = Aws::S3::Resource.new.bucket(ENV['S3_BUCKET'])

另外,两个预签名-post对象的区别:

"x-amz-credential"=>"<MY_ACCESS_KEY>/20180505/us-east-1/s3/aws4_request"

"x-amz-credential"=>"/20180505/us-east-1/s3/aws4_request"

你不应该在你的 git 存储库中提交你的凭据,所以你应该在你的初始化程序中确保:

在config/initializers/credentials.rb

AWS_ACCESS_KEY_ID = ENV['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = ENV['AWS_SECRET_ACCESS_KEY']

并使用 heroku-cli 在您的应用程序上配置您的凭据

heroku config:set AWS_ACCESS_KEY_ID=someLongHashKey AWS_SECRET_ACCESS_KEY=anotherLongHashKey --app my_app_name
# see heroku config --help

但是你的错误可能与

有关

并查看 https://docs.aws.amazon.com/sdkforruby/api/Aws/S3/PresignedPost.html

如果这没有帮助,post你是如何定义的Aws::S3::PresignedPost.new

最后,仔细检查以确保您在 heroku 中正确设置了环境变量

heroku config --app my_app_name #use your actual app name of course