我使用aws-sdk-core gem我在获取url表单aws时遇到错误
以下是我的代码
以下是我的代码
def initialize(bucket:,region:) @bucket = bucket client = Aws::S3::Client.new(region: region) @signer = Aws::S3::Presigner.new(client: client) end def sign(key,expires_in: 3600) @signer.presigned_url(:get_object,bucket: @bucket,key: key,expires_in: expires_in) end
我收到了错误
NoMethodError - undefined method `credentials' for nil:NilClass: aws-sdk-core (2.1.15) lib/aws-sdk-core/signers/v4.rb:24:in `initialize' aws-sdk-core (2.1.15) lib/aws-sdk-core/s3/presigner.rb:88:in `block in sign_but_dont_send'
如果有人知道如何获得预先签名的网址,请让我们知道
谢谢
解决方法
无用的错误消息表明您尚未配置AWS凭据.这些都需要生成签名.如果您使用客户端发送请求,您将收到一条更有用的错误消息,指出需要凭据.
def initialize(bucket:,region:) @bucket = bucket creds = Aws::Credentials.new('ACCESS_KEY','SECRET_ACCESS_KEY') client = Aws::S3::Client.new(region: region,credentials,creds) @signer = Aws::S3::Presigner.new(client: client) end def sign(key,expires_in: 3600) @signer.presigned_url(:get_object,expires_in: expires_in) end
与您的问题无关,但您可以使用S3的资源接口来清理代码.
def initialize(bucket:,region:) @bucket = Aws::S3::Bucket.new(bucket,{ region: region,credentials: Aws::Credentials.new('ACCESS_KEY','SECRET_ACCESS_KEY'),}) end def sign(key,expires_in: 3600) @bucket.object(key).presigned_url(:get,expires_in: expires_in) end
虽然我展示了如何在代码中配置凭据,但我强烈建议不要这样做.您应该在启动应用程序之前将凭据导出到ENV,或将它们放在共享凭证文件中.
$export AWS_ACCESS_KEY_ID=... $export AWS_SECRET_ACCESS_KEY=...
或者将以下内容放在〜/ .aws / credentials中
[default] aws_access_key_id=... aws_secret_access_key=...