LoginSignup
0
0

More than 3 years have passed since last update.

node.jsでgoogleapiのリダイレクトURIに任意の文字列(state)を追加する方法

Posted at

この記事について

バックエンドで Google API を使っています。
言語はNode.jsで書いています。
Google APIの使用には、Google APIs Node.js Client
を使っています。

今回は、Google APIのユーザー認証後のリダイレクトURIに任意の文字列を指定する方法を記載します。

事前準備

GCPコンソールにてGoogleプロジェクトを作成し、認証情報を作成し、何かしらのAPIを有効化しておいてください。
↓GCPコンソール(developers)
https://console.developers.google.com/apis

やり方

リダイレクトURLに任意の文字列を含めたい場合は、stateパラメータを認証URLに含めることで可能です。
https://developers.google.com/identity/protocols/oauth2/web-server#request-parameter-state

(ちなみに)stateパラメータの用途

You can use this parameter for several purposes, such as directing the user to the correct resource in your application, sending nonces, and mitigating cross-site request forgery.

日本語訳
stateパラメータは下記のような目的で利用されます。
・ユーザーをアプリの正しいリソースにリダイレクトするため
・乱数を送るため
・CSRF対策のため

実際の認証URL例

公式ドキュメントにも書いてありますが、こんな感じで認証URLにstateを含めます。

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly&
 access_type=offline&
 response_type=code&
 state=state_parameter_passthrough_value&
 redirect_uri=https%3A//oauth2.example.com/code&
 client_id=client_id

Node.jsでの実装例

useGoogleApi.js
const { google } = require("googleapis");

const oauth2Client = new google.auth.OAuth2(
  CLIENT_ID,
  CLIENT_SECRET,
  REDIRECT_URI
);

const scopes = "https://www.googleapis.com/auth/blogger";

const authUrl = oauth2Client.generateAuthUrl({
  access_type: "offline",
  scope: scopes,
  state: "abcdefghijklmnopqrstuvwxuz", // ←任意の文字列
});

console.log(authUrl)
useGoogleApi.jsがあるフォルダで下記コマンドを実行
node useGoogleApi.js
するとこんな感じでURLがコンソールに出力されるので、そのURLにアクセスする。
https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fblogger&state=abcdefghijklmnopqrstuvwxuz&response_type=code&client_id=your_client_id&redirect_uri=your_redirect_uri

認証画面にてGoogleアカウントを選択すると
リダイレクトしたURLにちゃんとstateが渡されていました^^

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