1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[aws-sdk S3] 署名付きURLの発行

Posted at

業務でS3の署名付きURL(GetObject)を発行を行いました。
備忘録として残しておきます。

環境

Docker node:16-alpine
"typescript": "^4.5.4"
"@aws-sdk/client-s3": "^3.46.0",
"@aws-sdk/s3-request-presigner": "^3.47.0",

結論

s3.ts
import {
  GetObjectCommand,
  S3Client,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

const client = new S3Client({
  region: 'ap-northeast-1',
});

/**
 * 署名付きURLを発行する
 *
 * @param bucket
 * @param key
 * @param expiresIn
 * @returns 署名付きURL
 */
const getPresignedUrl = async (bucket: string, key: string, expiresIn: number): Promise<string> => {
  const objectParams = {
    Bucket: bucket,
    Key: key,
  };
  const url = await getSignedUrl(client, new GetObjectCommand(objectParams), { expiresIn });
  console.log(url)
  return url
};

export { getPresignedUrl }

前提

  • IAMRole等の設定を行なって、対象のs3バケットに対して以下の権限があること
"Action": ["s3:GetObject"]

これで動かなかったらs3:ListBucketもいるかも

  • 以下のコマンドを実行し、必要なパッケージをインストールしておくこと
> npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner

解説

  • 引数
    • bucket: URLを発行したいS3バケット
    • key: URLを発行したS3バケット内のオブジェクトキー
    • expiresIn: 署名を有効にしておきたい時間(単位は秒)

上記のコードを実行して、ブラウザ上でURLにアクセスすれば、ファイルがローカルにダウンロードされます。
参考記事の1つ目を参考にすれば、putObjectも同様にできそうですね〜。

参考
https://aws.amazon.com/jp/blogs/developer/generate-presigned-url-modular-aws-sdk-javascript/
https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/modules/_aws_sdk_s3_request_presigner.html

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?