Google が ID トークンを返すと、HTTP POST
メソッド リクエストによって、パラメータ名 credential
とともにログイン エンドポイントに送信されます。
次の例は、ID トークンを検証して使用する一般的な手順を示しています。
クロスサイト リクエスト フォージェリ(CSRF)トークンを検証します。ログイン エンドポイントに認証情報を送信する際は、CSRF 攻撃を防ぐためにダブル送信 Cookie パターンを使用します。送信のたびにトークンが生成されます。次に、次のコード例に示すように、トークンが Cookie と POST 本文の両方に配置されます。
csrf_token_cookie = self.request.cookies.get('g_csrf_token') if not csrf_token_cookie: webapp2.abort(400, 'No CSRF token in Cookie.') csrf_token_body = self.request.get('g_csrf_token') if not csrf_token_body: webapp2.abort(400, 'No CSRF token in post body.') if csrf_token_cookie != csrf_token_body: webapp2.abort(400, 'Failed to verify double submit cookie.')
ID トークンを検証します。
トークンが有効であることを確認するには、次のことを確認します。 条件が満たされます。
- ID トークンが Google によって適切に署名されている。Google の公開鍵を使用する
(
JWK または
PEM 形式)
トークンの署名を検証します。これらの鍵は定期的にローテーションされます。調べる
レスポンスの
Cache-Control
ヘッダーを使用して、 再度取得する必要があります - ID トークンの
aud
の値がアプリのいずれかの値と等しい クライアント ID などがあります。このチェックは、悪意のあるクライアントに ID トークンを発行するのを防ぐために必要です。 アプリが、アプリのバックエンド サーバー上の同一ユーザーに関するデータにアクセスするために使用されています。 - ID トークンの
iss
の値は次と等しいaccounts.google.com
またはhttps://accounts.google.com
。 - ID トークンの有効期限(
exp
)を過ぎていない。 - ID トークンが Google Workspace または Cloud
組織アカウントの場合は、
hd
クレームを確認できます。これは、ホストされている Pod が ユーザーのドメインです。これは、リソースへのアクセスをそのメンバーのみに制限する場合に できます。このクレームがない場合、アカウントは Google がホストするドメイン。
email
、email_verified
、hd
フィールドを使用して、 Google はメールアドレスをホストし、その権威があります。Google が信頼できる場合、 そのユーザーが正当なアカウント所有者であることがわかっているため、パスワードやその他の 確認しましょう。Google が信頼できるケース:
email
には@gmail.com
という接尾辞が付いています。これは Gmail アカウントです。email_verified
は true で、hd
が設定されています。これは G Suite アカウントです。
ユーザーは Gmail や G Suite を使用せずに Google アカウントを登録できます。日時
email
に@gmail.com
という接尾辞がなく、hd
が存在しないと、Google にはありません。 認証には、信頼できる認証方法、パスワード、その他の本人確認方法を使用することが推奨されます。 できます。email_verified
も、Google が最初に検証した ユーザーに付与できますが、サードパーティの所有権が付与されます。 アカウントが変更された可能性があります。これらの検証ステップを実行するために独自のコードを記述するのではなく、 プラットフォームに適した Google API クライアント ライブラリを使用するか、 JWT ライブラリ。開発とデバッグの場合は、
tokeninfo
を呼び出すことができます。 検証エンドポイントを指定します。Using a Google API Client Library
Using one of the Google API Client Libraries (e.g. Java, Node.js, PHP, Python) is the recommended way to validate Google ID tokens in a production environment.
Java To validate an ID token in Java, use the GoogleIdTokenVerifier object. For example:
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload; import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; ... GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory) // Specify the WEB_CLIENT_ID of the app that accesses the backend: .setAudience(Collections.singletonList(WEB_CLIENT_ID)) // Or, if multiple clients access the backend: //.setAudience(Arrays.asList(WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3)) .build(); // (Receive idTokenString by HTTPS POST) GoogleIdToken idToken = verifier.verify(idTokenString); if (idToken != null) { Payload payload = idToken.getPayload(); // Print user identifier String userId = payload.getSubject(); System.out.println("User ID: " + userId); // Get profile information from payload String email = payload.getEmail(); boolean emailVerified = Boolean.valueOf(payload.getEmailVerified()); String name = (String) payload.get("name"); String pictureUrl = (String) payload.get("picture"); String locale = (String) payload.get("locale"); String familyName = (String) payload.get("family_name"); String givenName = (String) payload.get("given_name"); // Use or store profile information // ... } else { System.out.println("Invalid ID token."); }
The
GoogleIdTokenVerifier.verify()
method verifies the JWT signature, theaud
claim, theiss
claim, and theexp
claim.If you need to validate that the ID token represents a Google Workspace or Cloud organization account, you can verify the
hd
claim by checking the domain name returned by thePayload.getHostedDomain()
method. The domain of theemail
claim is insufficient to ensure that the account is managed by a domain or organization.Node.js To validate an ID token in Node.js, use the Google Auth Library for Node.js. Install the library:
Then, call thenpm install google-auth-library --save
verifyIdToken()
function. For example:const {OAuth2Client} = require('google-auth-library'); const client = new OAuth2Client(); async function verify() { const ticket = await client.verifyIdToken({ idToken: token, audience: WEB_CLIENT_ID, // Specify the WEB_CLIENT_ID of the app that accesses the backend // Or, if multiple clients access the backend: //[WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3] }); const payload = ticket.getPayload(); const userid = payload['sub']; // If the request specified a Google Workspace domain: // const domain = payload['hd']; } verify().catch(console.error);
The
verifyIdToken
function verifies the JWT signature, theaud
claim, theexp
claim, and theiss
claim.If you need to validate that the ID token represents a Google Workspace or Cloud organization account, you can check the
hd
claim, which indicates the hosted domain of the user. This must be used when restricting access to a resource to only members of certain domains. The absence of this claim indicates that the account does not belong to a Google hosted domain.PHP To validate an ID token in PHP, use the Google API Client Library for PHP. Install the library (for example, using Composer):
Then, call thecomposer require google/apiclient
verifyIdToken()
function. For example:require_once 'vendor/autoload.php'; // Get $id_token via HTTPS POST. $client = new Google_Client(['client_id' => $WEB_CLIENT_ID]); // Specify the WEB_CLIENT_ID of the app that accesses the backend $payload = $client->verifyIdToken($id_token); if ($payload) { $userid = $payload['sub']; // If the request specified a Google Workspace domain //$domain = $payload['hd']; } else { // Invalid ID token }
The
verifyIdToken
function verifies the JWT signature, theaud
claim, theexp
claim, and theiss
claim.If you need to validate that the ID token represents a Google Workspace or Cloud organization account, you can check the
hd
claim, which indicates the hosted domain of the user. This must be used when restricting access to a resource to only members of certain domains. The absence of this claim indicates that the account does not belong to a Google hosted domain.Python To validate an ID token in Python, use the verify_oauth2_token function. For example:
from google.oauth2 import id_token from google.auth.transport import requests # (Receive token by HTTPS POST) # ... try: # Specify the WEB_CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token, requests.Request(), WEB_CLIENT_ID) # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request()) # if idinfo['aud'] not in [WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3]: # raise ValueError('Could not verify audience.') # If the request specified a Google Workspace domain # if idinfo['hd'] != DOMAIN_NAME: # raise ValueError('Wrong domain name.') # ID token is valid. Get the user's Google Account ID from the decoded token. userid = idinfo['sub'] except ValueError: # Invalid token pass
The
verify_oauth2_token
function verifies the JWT signature, theaud
claim, and theexp
claim. You must also verify thehd
claim (if applicable) by examining the object thatverify_oauth2_token
returns. If multiple clients access the backend server, also manually verify theaud
claim.- ID トークンが Google によって適切に署名されている。Google の公開鍵を使用する
(
JWK または
PEM 形式)
トークンの署名を検証します。これらの鍵は定期的にローテーションされます。調べる
レスポンスの
トークンの有効性が確認できたら、Google ID トークンの情報を使用して、サイトのアカウント ステータスを関連付けることができます。
未登録のユーザー: 必要に応じて、ユーザーが追加のプロファイル情報を提供できる登録ユーザー インターフェース(UI)を表示できます。また、ユーザーは新しいアカウントとログイン中のユーザー セッションをサイレントで作成することもできます。
サイトにすでに存在する既存のアカウント: エンドユーザーがパスワードを入力して、以前のアカウントを Google 認証情報にリンクできるウェブページを表示できます。これにより、ユーザーが既存のアカウントにアクセスできることを確認できます。
再びログインする連携ユーザー: ユーザーをサイレント ログインできます。