LoginSignup
22
20

More than 3 years have passed since last update.

firebase-adminからCloudStorageの署名付きURLの取得(getSignedUrl)ができるようにする設定

Last updated at Posted at 2019-07-24
1 / 11

CloudStorageにアップロードしたファイルにアクセスするURLが欲しい

File#getSignedUrlを使います。
https://cloud.google.com/nodejs/docs/reference/storage/2.5.x/File#getSignedUrl
でも設定足りてないとエラーになるよ、というお話。


話それるけど

@google-cloud/storageのAPIリファレンスはここに誘導されるけどなぜか開けない…
https://googleapis.dev/nodejs/storage/latest


話それるけど2

アップロードはこんな感じでできます

const admin = require('firebase-admin');
admin.initializeApp();
const bucket = admin.storage().bucket();
(中略)
await bucket.upload(file, {
  destination: 'dir/image.png',
  gzip: true,
  metadata: {
    cacheControl: 'public, max-age=31536000',
    contentType: 'image/png',
  },
});

getSignedUrl

デフォルトだとCloudStorage上のファイルはprivateなので読めない。(403エラー)
getSignedUrlで読めるURLを取得する。
失効時間指定もできる。


getSignedUrlしてみる

// 10分間だけ有効
const url = await bucket.file('dir/image.png').getSignedUrl({
  action: 'read',
  expires: moment().utc().add(10, 'minutes').format(),
});

エラーになることがある その1

Error: A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account.
This may be because the Compute Engine instance does not have the correct permission scopes specified.
Identity and Access Management (IAM) API has not been used in project 566029xxxxxx before or it is disabled.
Enable it by visiting
 https://console.developers.google.com/apis/api/iam.googleapis.com/overview?project=566029xxxxxx
 then retry.
If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.

エラーメッセージに記載されたURLにアクセスし、指示の通りにIAM APIを有効化しましょう。
README_img_enable-IAM-API.png


エラーになることがある その2

Error: A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account.
This may be because the Compute Engine instance does not have the correct permission scopes specified.
Permission iam.serviceAccounts.signBlob is required to perform this operation on service account
 projects/XXsome-projectXX/serviceAccounts/XXsome-projectXX@appspot.gserviceaccount.com.

ちょっと何言ってるかわかりません…
ググったらこういうことらしいです。

<プロジェクト名>@appspot.gserviceaccount.com(App Engine default service account)にサービスアカウントトークン作成者roleをつける

iam.serviceAccounts.signBlobの権限をもつroleを新たに作ったほうがいいのかもしれませんが、サービスアカウントトークン作成者だけがこの権限を持っていたのでこれを付けることにしました。

README_img_add-IAM-ROLE.png


以上で解決しました

コードの修正は必要ありませんでした。
めでたしめでたし。

参考: https://medium.com/@hiranya911/firebase-create-custom-tokens-without-service-account-credentials-d6049c2d2d85#772f

22
20
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
22
20