Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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 で認証させています。

zaru
basicinc
マーケティングとテクノロジーで社会のあらゆる問題を解決する集団
https://tech.basicinc.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした