はじめに
Google App Engine (GAE) を運用する場合通常サービスアカウントを使用しますが、サービスアカウントから個人の Gmail などにアクセスする際には別途 OAuth 認証を行って Access Token、Refresh Token を取得する必要があるため、その手順のメモ
OAuth クライアント ID の取得
Authorization Code 取得
Webブラウザで下記 URL にアクセスする
https://accounts.google.com/o/oauth2/auth?client_id=12345-xxxxx.apps.googleusercontent.com&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://mail.google.com/&response_type=code&approval_prompt=force&access_type=offline
client_id は上で取得したもの
scope は例として Gmail API のものを指定している。他の API を使う場合はに適宜変更すること
ブラウザに認証コードが表示されるのでメモする
scope を複数指定する場合
下記のように %20 で区切って指定する
scope=https://mail.google.com/%20https://www.googleapis.com/auth/datastore
Access Token 取得
上で取得した Authorization Code を使って Access Token を取得する (code で指定)
curl -k -d client_id=12345-xxxxx.apps.googleusercontent.com -d client_secret=xxxxx -d redirect_uri=urn:ietf:wg:oauth:2.0:oob -d grant_type=authorization_code -d code=xxxxx https://accounts.google.com/o/oauth2/token
下記JSONがレスポンスで返されるので access_token、refresh_token をメモする
{ "access_token" : "xxxxx...", "token_type" : "Bearer", "expires_in" : 3600, "refresh_token" : "xxxxx..." }