GCPサービスアカウントの p12 ファイルから token を取得する
サービスアカウントの JSON やAPIキーを使用した token の取得方法はそこそこ見つかったけど、 p12 ファイルを使用した場合のやりかたを探すのにだいぶ遠回りしたのでメモ。
使用するのはこれ
準備
const { GoogleToken } = require('gtoken'); const gtoken = new GoogleToken({ keyFile: 'path/to/key.pem', // or path to .p12 key file email: 'my_service_account_email@developer.gserviceaccount.com', scope: ['https://scope1', 'https://scope2'] // or space-delimited string of scopes });
- keyFIle ・・・ p12 や pem でも大丈夫らしい ※ pem は未確認
- email ・・・ サービスアカウントの email
- scope ・・・ auth 対象のサービス群を列挙、配列形式のほかスペース区切りの文字列でも可とのこと
token 取得
Promise 返ってくるので、 await するか then で受けるか
const tokens = await gtoken.getToken()
console.log(tokens);
gtoken.getToken() .then(tokens => { console.log(tokens) }) .catch(console.error);
補足
json ファイルでの認証や、秘密鍵からの認証も用意されている
https://github.com/googleapis/node-gtoken#use-with-a-service-account-json-key-file https://github.com/googleapis/node-gtoken#pass-the-private-key-as-a-string-directly