2023-10-16

Python: GoogleのOAuth認証の仕組みを理解する

すぐ忘れてしまうのでメモ書き。Googleのサービスにアクセスする際には、次の手順が必要です。なお、本記事は、GoogleClassroomAPI を利用する過程での処理なので、適時読み替えてください。

Google Cloud コンソールの設定と認証ファイルの作成
まずは、Google Cloudコンソールで、GoogleClassroomAPIを使えるようにしないといけません。詳細の手続きは、公式サイトを参照してください。ここで、大切なのは

  • Google Cloudプロジェクトを作成しておく(以下、全てこのプロジェクト内での操作になります)
  • Google Classroom API を有効にする(利用したいAPIをONにしましょう。細かな権限設定もできます)
  • 「APIとサービス」のところで認証情報に移動し、認証ファイルを作成しダウンロード
Google クライアントPythonライブラリのインストール
先程の公式サイトに書いてあるので、pip でインストールしましょう。

サンプルコードの実行
下記は、公式サイトの一部を抜粋したものです。ここで理解しておくべきことは、認証ファイルとトークンファイルについてです。
  • 認証ファイルは上記でダウンロードしたファイルです。コード内のcredentials.jsonに相当します
  • トークンファイルは、このコードを実行することで生成されるファイルです。このコードを実行するとブラウザが立ち上がり、認証を求められます。認証を済ませると、token.jsonファイルが作成されます。このトークンファイルは古くなると使えなくなるので定期的に消して書き換えることになるのだと思います
注意点
トークンファイル(token.json)は、スコープに関係しています。Google Cloud コンソールにてプロジェクトで扱えるスコープを設定したと思いますが、クライアント側(コード内)でも指定しないといけません。それが、コード内でのSCOPES変数に相当します。下記のサンプルでは、1つだけ指定してますが、配列として複数指定することは可能です。ここに書いたSCOPESに対応したトークンファイルが出来上がることになります。ですので、SCOPESを変更するときは、トークンファイルを消して再度生成し直してください。

from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
##SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly']
def main():
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())


0 件のコメント:

コメントを投稿