0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[OAuth2] 認可コードフロー

Last updated at Posted at 2021-08-14

1. OAuth同意画面の作成

  • GCPコンソールから「APIとサービス」 > 「OAuth同意画面」を開く
  • 「内部」 or 「外部」の選択 => 今回はテスト目的のため「内部」を選択
  • アプリ名、ユーザサポートメール、デベロッパーの連絡先情報を埋める
  • スコープを選択 => 今回はBigQuery APIを選択 (.../auth/bigquery)

2. OAuthクライアントIDの作成

  • GCPコンソールから「APIとサービス」 > 「認証情報」を開く
  • 「認証情報を作成」 > 「OAuthクライアントID」を選択
  • アプリケーションの種類から「デスクトップアプリ」を選択 (今回はCLIで認可コードフローを確認するのが目的のためデスクトップにする)

3. 認可コードの取得

認可エンドポイント

https://accounts.google.com/o/oauth2/v2/auth

クエリパラメータ

% CLIENT_ID=<CLIENT_ID>
% CLIENT_SECRET=<CLIENT_SECRET>
% REDIRECT_URI=$(echo "urn:ietf:wg:oauth:2.0:oob" | nkf -WwMQ | sed 's/=$//g' | tr = % | tr -d '\n')
% SCOPE=$(echo "https://www.googleapis.com/auth/bigquery" | nkf -WwMQ | sed 's/=$//g' | tr = % | tr -d '\n')
% echo "https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=$REDIRECT_URI&prompt=consent&response_type=code&client_id=$CLIENT_ID&scope=$SCOPE&access_type=offline"

出力されたURLをブラウザで開くとOAuth同意画面にリダイレクトされ、同意すると認可コードが取得できる。

スクリーンショット 2021-03-20 22.07.22.png

4. アクセストークン、リフレッシュトークンの取得

% CODE=$(echo "4/1AY0e-g5vTPqy0-6gGP7MiYyd9FUDFfVDdFU4v-_yI15D3ZtHIeKCbnZBPRM"|nkf -WwMQ|sed 's/=$//g'|tr = %|tr -d '\n')
% curl -XPOST 'https://oauth2.googleapis.com/token' -d "code=$CODE&redirect_uri=$REDIRECT_URI&client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET&scope=&grant_type=authorization_code"
{
  "access_token": "ya29.a0AfH6SMCGmatgsCNMzX5sCPAwISaFz3UZi5Q77sYeCDPCpCaVzw6ymzwFfbyk7aMiZO-tbfG1HHcKwYs3U336KpYZI5c3kOrtKPknaGtRyF8FghyhLIg_tgeBJEnH-Hy7BvrjF45Dl4d3PWkyRDDlu_r7XsDo",
  "expires_in": 3599,
  "refresh_token": "1//0eDwYfG3QKMPACgYIARAAGA4SNwF-L9IrpGmFDTnZWifWByUxc9UMq_xxBN7v6d-G3_9SEePoc3Pp5TFAXcICBTDL3wjfI3Pr2TU",
  "scope": "https://www.googleapis.com/auth/bigquery",
  "token_type": "Bearer"
}

5. アクセストークンの更新

% REFRESH_TOKEN=$(echo "1//0eDwYfG3QKMPACgYIARAAGA4SNwF-L9IrpGmFDTnZWifWByUxc9UMq_xxBN7v6d-G3_9SEePoc3Pp5TFAXcICBTDL3wjfI3Pr2TU"|nkf -WwMQ|sed 's/=$//g'|tr = %|tr -d '\n')
% curl -XPOST 'https://oauth2.googleapis.com/token' -d "client_secret=$CLIENT_SECRET&grant_type=refresh_token&refresh_token=$REFRESH_TOKEN&client_id=$CLIENT_ID"

6. アクセストークンの取り消し

curl 'https://accounts.google.com/o/oauth2/revoke?token=<access_token>'
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?