LoginSignup
6
2

More than 5 years have passed since last update.

GoogleAPI SDK ServiceAccount認証コード(Ruby or Node.js)

Posted at

Google (GSuite) の API を使ってゴニョゴニョするとき、認証が必要になります。今回は Service Account を使ってユーザに依存しない方法で認証をするやり方をメモしておきます。すごく彷徨ったので、未来の自分のために。

Service Account と認証に使う JSON ファイルの作成方法は、巷にあふれているので参照してください。

Ruby

require 'google/apis/admin_directory_v1'
require 'googleauth'

# Service Account 作成時に作った認証 JSON ファイル
ENV['GOOGLE_APPLICATION_CREDENTIALS'] = './client_secrets_sample.json'

scope = [
  'https://www.googleapis.com/auth/admin.directory.user'
]

authorization = Google::Auth.get_application_default(scope)
# sub に組織に所属するだれかのメールアドレスを指定する必要がある
authorization.sub = 'user@example.com'

service = Google::Apis::AdminDirectoryV1::DirectoryService.new
service.authorization = authorization

# あとは利用したいリソースを実行すれば OK

Node.js

import * as googleapis from 'googleapis'

const scope = [
  'https://www.googleapis.com/auth/calendar',
]

const jwtClient = new googleapis.google.auth.JWT(
  null,
  './client_secrets_sample.json',
  null,
  scope,
  'user@example.com', // Ruby と同様に sub 指定をする必要がある
)

jwtClient.authorize()

const calendar = googleapis.google.calendar('v3')

calendar.calendarList.list({
  auth: jwtClient, // 実行時に都度渡す
}).then((res: any) => {
  console.log(res.data.items)
})

Node.js のほうでは application_default を使った認証がうまく行かなかったので普通に JWT で認証させています。

6
2
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
6
2