LoginSignup
7
8

More than 1 year has passed since last update.

Google DriveのAPIをサービスアカウント認証方式でNode.jsから利用するメモ

Last updated at Posted at 2022-04-02

前回書いた記事で調べていて、サービスアカウントを利用する方式も試してみたので記録しておきます。

Google DriveのAPIをNode.jsで触る ~ @google-cloud/local-authのサンプル版

前提など

環境

1. サービスアカウント利用の準備

こちらの記事が分かりやすかったです。

参考: NodeでGoogle Drive, Cloud Storage, Gmailを使ったアプリ開発(主に認証)

1-1. サービスアカウントの作成

APIとサービスのメニューから認証情報を作成 -> サービスアカウントと進みます。

サービスアカウントの名前を入れて完了で進みます。

サービスアカウントが作成されました。メールアドレスが発行されます。

作成したサービスアカウントに権限を付与します。新しいプリンシパルの部分に先ほど発行されたメールアドレスを指定しましょう。ロールはプロジェクト => オーナーにして保存します。

1-2. キーの発行

スクリーンショット 2022-04-03 5.37.35.png

サービスアカウントのキーを発行します。

JSON形式で保存します。

credentials.jsonという名前にして保存するとサンプルを試しやすいです。

1-3. 利用するGoogle Driveのフォルダにサービスアカウントの権限を付与

サービスアカウントを編集者にしてGoogle Driveに追加します。

2. サービスアカウントのキーで認証

ライブラリをインストールします。

npm i googleapis@100

こちらのドキュメントを参考にサービスアカウント利用のコードに修正してみました。

https://github.com/googleapis/google-api-nodejs-client#service-account-credentials

以下のようなコードになりました。

'use strict';

const path = require('path');
const {google} = require('googleapis');

async function runSample(query) {

  const auth = new google.auth.GoogleAuth({
    keyFile: path.join(__dirname, './.private/credentials.json'),
    scopes: ['https://www.googleapis.com/auth/drive.metadata.readonly'],
  });

  const drive = google.drive({version: 'v3', auth: auth});
  
  const params = {pageSize: 3};
  params.q = query;
  const res = await drive.files.list(params);
  console.log(res.data);
  return res.data;
}

if (module === require.main) {
  runSample().catch(console.error);
}
module.exports = runSample;

実行すると見事にファイルリストが取得できました。

$ node app.js
{
  kind: 'drive#fileList',
  nextPageToken: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  incompleteSearch: false,
  files: [
    {
      kind: 'drive#file',
      id: '1QBZPkNxxxxxxxxxxxxxxxxxxxx'

省略   

特にリダイレクトURLなど無しで利用できました。

前回(Google DriveのAPIをNode.jsで触る ~ @google-cloud/local-authのサンプル版)のサンプルだと毎回認証が発生して少し手間でしたが、こちらの方式だと手間が少なそうです。

7
8
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
7
8