LoginSignup
33
27

More than 5 years have passed since last update.

Ruby AWS SDK v2 でS3の署名付きURLを発行する

Posted at

Aws::S3::Presignerを使います。

基本

s3 = Aws::S3::Client.new
signer = Aws::S3::Presigner.new(client: s3)
signer.presigned_url(:get_object, 
                     bucket: 'your-bucket',
                     key: 'path/to/object')

URLの有効期限を設定する

たとえば、購入者に向けてダウンロード用URLを発行する場合、不正利用を防ぐためにごく短期間のURLを作りたい。

そういったときはexpires_inで指定できる。

以下、30秒だけアクセス可能なURLの例

signer.presigned_url(:get_object, 
                     bucket: 'your-bucket',
                     key: 'path/to/object', 
                     expires_in: 30)

HTTPSにしたい

secure: trueを指定する。

signer.presigned_url(:get_object, 
                     bucket: 'your-bucket',
                     key: 'path/to/object', 
                     secure: true)

Content-Typeを指定する

たとえば、S3のファイルを直接ブラウザで開くのではなく、ダウンロードさせたいときapplication/force-downloadを設定する。

S3ではresponse-content-typeをリクエストパラメータに追加して署名すれば良いみたい。

参考:
http://docs.aws.amazon.com/ja_jp/AmazonS3/latest/API/RESTObjectGET.html

サンプルが見つからず苦労したものの、コードを読むと単に以下のようにすればよいようだった。

signer.presigned_url(:get_object, 
                     bucket: 'your-bucket',
                     key: 'path/to/object', 
                     response_content_type: 'application/force-download')

ダウンロードファイル名を指定したい(Content-Disposition)

Content-Typeの時と同様に、response_content_dispositionを指定する。

signer.presigned_url(:get_object, 
                     bucket: 'your-bucket',
                     key: 'path/to/object', 
                     response_content_disposition: 'attachment; filename=Downloadfile.pdf')
33
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
27