Google APIで使用するRefreshTokenを取得する
おさらい
PythonでOAuth2.0とFusionTablesAPIを実行する手順まとめの続き。
Google APIを使用するためには、まずGoogleアカウントが必要。
- ID(メールアドレス)
- パスワード
APIを使う前にOAuth2.0の認証が必要である。そのために以下のようなキーが必要。
- ClientId
- ClientSecret
- API Key
- code
- AccessToken
今回
AccessTokenは有効期限があるため一定期間ごとに取得する必要があるらしい。しかし手動で操作を行わねばならない。面倒。
そこで、RefreshTokenを使って手動操作を省いたAccessTokenの取得を検討したい。
全体では「Googleアカウント→GoogleDeveloperConsole→ClientId,ClientSecret,ApiKey→RefreshToken→AccessToken→Google API」という流れでAPIを使用できる。(長すぎる…)
RefreshTokenを取得する
RefreshTokenを取得してファイルに保存する。
ソースコード
GetRefreshToken.py
#!python2 #encoding:utf-8 import urllib2, urllib, simplejson, sys, httplib import codecs client_id = "aaaaaaaaaaaaaaaaaaaaaaaaaa.apps.googleusercontent.com" client_secret = "bbbbbbbbbbbbbbbbbbbbb" redirect_uri = "http://localhost:8000" class RunAPITest: def __init__(self): def main(self): print "copy and paste the url below into browser address bar and hit enter" print "https://accounts.google.com/o/oauth2/auth?%s%s%s%s" % \ ("client_id=%s&" % (client_id), "redirect_uri=%s&" % (redirect_uri), "scope=https://www.googleapis.com/auth/fusiontables&", "response_type=code") code = raw_input("Enter code (parameter of URL): ") data = urllib.urlencode({ "code": code, "client_id": client_id, "client_secret": client_secret, "redirect_uri": redirect_uri, "grant_type": "authorization_code" }) serv_req = urllib2.Request(url="https://accounts.google.com/o/oauth2/token", data=data) serv_resp = urllib2.urlopen(serv_req) response = serv_resp.read() filePath = "Google.OAuth2.Token.{0}.json".format(client_id) file = codecs.open(filePath, 'w', 'utf-8') file.write(response) file.close() if __name__ == "__main__": api_test = RunAPITest() api_test.main()
client_idとclient_secretに取得した値を設定する。
実行
PythonでOAuth2.0とFusionTablesAPIを実行する手順まとめのときと同様の手順である。以下のようにざっとおさらいする。
ローカルサーバ起動
- コンソールを起動する
- 以下のコマンドを実行する
Python2の場合
python -m SimpleHTTPServer [ポート番号(デフォルトは8000)]
Python3の場合
python3 -m http.server [ポート番号(デフォルトは8000)]
ソースコードを実行する
- コンソールを起動する
python GetRefreshToken.py
コマンドを実行する
手続きをする
copy and paste the url below into browser address bar and hit enter https://accounts.google.com/o/oauth2/auth?client_id=aaaaaaaaaaaaaaaaaaaaaaaaaa.apps.googleusercontent.com&redirect_uri=http://localhost:8000&scope=https://www.googleapis.com/auth/fusiontables&response_type=code Enter code (parameter of URL):
- 上記のような表示が出るので、URL部分をコピーする。 上記の例でいうと「https://accounts.google.com/o/oauth2/auth?client_id=aaaaaaaaaaaaaaaaaaaaaaaaaa.apps.googleusercontent.com&redirect_uri=http://localhost:8000&scope=https://www.googleapis.com/auth/fusiontables&response_type=code」の部分。
- 許可ボタンを押下する。
- URLに
code=...
の部分があるのでその値をコピーする。 - それをコンソールの「Enter code (parameter of URL):」の後ろに貼り付ける。
- Enterキーを押下する。
Google.OAuth2.Token.{CliendId}.json
ファイルが作成されるrefresh_token
の値が目的のものである
取得されるファイルは以下のようなもの。
{ "access_token" : "cccccccccccccccccccccccccccccccccccccccccccccccccccccc", "expires_in" : 3600, "refresh_token" : "dddddddddddddddddddddddddddddddddddddddd", "token_type" : "Bearer" }
設定したClientIdのrefresh_tokenが取得できた。
以後、そのClientIdでAccessTokenがほしいときは、このrefresh_tokenを使う。
こちらによるとexpires_in
3600とは、3600秒(1時間)後にAccessTokenが失効するという意味らしい。感謝。
AccessTokenを取得する
RefreshTokenからAccessTokenを取得する。
こちらを参考にした。感謝。
set CLIENT_ID=aaaaaaaaaaaaaaaaaaaaaaaaaa.apps.googleusercontent.com set CLIENT_SECRET=bbbbbbbbbbbbbbbbbbbbb set REFRESH_TOKEN=dddddddddddddddddddddddddddddddddddddddd set CURL_PEM="C:\root\downloads\cacert.pem" curl -k --cacert %CURL_PEM% --data "refresh_token=%REFRESH_TOKEN%" --data "client_id=%CLIENT_ID%" --data "client_secret=%CLIENT_SECRET%" --data "grant_type=refresh_token" https://www.googleapis.com/oauth2/v4/token
以下のように取得される。
{ "access_token": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "token_type": "Bearer", "expires_in": 3600 }
以後、AccessTokenの取得はこのバッチを叩けば可能。
課題
上記をもっとシームレスにやりたい。Googleアカウント、ClientId、RefreshTokenを紐付けて管理する必要がある。しかし一元管理するとセキュリティ面で問題になるか。
Python、CURL、ローカルサーバなど、ツギハギ感満載。もう少しまとめたい。
所感
とりあえずRefreshTokenの取得ができた。これでAccessTokenを手動操作なしで取得する目処が立った。