验证服务器端的 Google ID 令牌

Google 返回 ID 令牌后,系统会通过 HTTP POST 方法请求(参数名称为 credential)将该令牌提交到您的登录端点。

以下是一个 Python 语言示例,显示了验证和使用 ID 令牌的常规步骤:

  1. 验证跨站请求伪造 (CSRF) 令牌。当您将凭据提交到登录端点时,我们会使用双重提交 Cookie 模式来防止 CSRF 攻击。每次提交前,我们都会生成令牌。然后,将令牌同时放入 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.')
    
  2. 验证 ID 令牌。

    To verify that the token is valid, ensure that the following criteria are satisfied:

    • The ID token is properly signed by Google. Use Google's public keys (available in JWK or PEM format) to verify the token's signature. These keys are regularly rotated; examine the Cache-Control header in the response to determine when you should retrieve them again.
    • The value of aud in the ID token is equal to one of your app's client IDs. This check is necessary to prevent ID tokens issued to a malicious app being used to access data about the same user on your app's backend server.
    • The value of iss in the ID token is equal to accounts.google.com or https://accounts.google.com.
    • The expiry time (exp) of the ID token has not passed.
    • 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.

    Rather than writing your own code to perform these verification steps, we strongly recommend using a Google API client library for your platform, or a general-purpose JWT library. For development and debugging, you can call our tokeninfo validation endpoint.

    使用 Google API 客户端库

    在生产环境中验证 Google ID 令牌时,建议使用一个 Google API 客户端库(例如 JavaNode.jsPHPPython)。

    Java

    要在 Java 中验证 ID 令牌,请使用 GoogleIdTokenVerifier 对象。例如:

    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 CLIENT_ID of the app that accesses the backend:
        .setAudience(Collections.singletonList(CLIENT_ID))
        // Or, if multiple clients access the backend:
        //.setAudience(Arrays.asList(CLIENT_ID_1, CLIENT_ID_2, 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.");
    }

    GoogleIdTokenVerifier.verify() 方法可验证 JWT 签名、aud 声明、iss 声明和 exp 声明。

    如果您需要验证该 ID 令牌代表的是 Google Workspace 或 Cloud 组织帐号,则可以通过检查 Payload.getHostedDomain() 方法返回的域名来验证 hd 声明。email 声明的网域不足以确保帐号由网域或组织管理。

    Node.js

    如需在 Node.js 中验证 ID 令牌,请使用 Node.js 版 Google Auth 库。安装库:

    npm install google-auth-library --save
    然后,调用 verifyIdToken() 函数。例如:

    const {OAuth2Client} = require('google-auth-library');
    const client = new OAuth2Client();
    async function verify() {
      const ticket = await client.verifyIdToken({
          idToken: token,
          audience: CLIENT_ID,  // Specify the CLIENT_ID of the app that accesses the backend
          // Or, if multiple clients access the backend:
          //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
      });
      const payload = ticket.getPayload();
      const userid = payload['sub'];
      // If request specified a G Suite domain:
      // const domain = payload['hd'];
    }
    verify().catch(console.error);
    

    verifyIdToken 函数会验证 JWT 签名、aud 声明、exp 声明和 iss 声明。

    如果您需要验证该 ID 令牌代表的是 Google Workspace 或 Cloud 组织帐号,则可以检查 hd 声明,该声明指示用户的托管网域。仅允许特定网域的成员访问资源时,必须使用此方法。缺少此声明表示帐号不属于 Google 托管的网域。

    PHP

    如需在 PHP 中验证 ID 令牌,请使用 PHP 版 Google API 客户端库。安装库(例如,使用 Composer):

    composer require google/apiclient
    然后,调用 verifyIdToken() 函数。例如:

    require_once 'vendor/autoload.php';
    
    // Get $id_token via HTTPS POST.
    
    $client = new Google_Client(['client_id' => $CLIENT_ID]);  // Specify the CLIENT_ID of the app that accesses the backend
    $payload = $client->verifyIdToken($id_token);
    if ($payload) {
      $userid = $payload['sub'];
      // If request specified a G Suite domain:
      //$domain = $payload['hd'];
    } else {
      // Invalid ID token
    }
    

    verifyIdToken 函数会验证 JWT 签名、aud 声明、exp 声明和 iss 声明。

    如果您需要验证该 ID 令牌代表的是 Google Workspace 或 Cloud 组织帐号,则可以检查 hd 声明,该声明指示用户的托管网域。仅允许特定网域的成员访问资源时,必须使用此方法。缺少此声明表示帐号不属于 Google 托管的网域。

    Python

    要在 Python 中验证 ID 令牌,请使用 verify_oauth2_token 函数。例如:

    from google.oauth2 import id_token
    from google.auth.transport import requests
    
    # (Receive token by HTTPS POST)
    # ...
    
    try:
        # Specify the CLIENT_ID of the app that accesses the backend:
        idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID)
    
        # Or, if multiple clients access the backend server:
        # idinfo = id_token.verify_oauth2_token(token, requests.Request())
        # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
        #     raise ValueError('Could not verify audience.')
    
        # If auth request is from a G Suite domain:
        # if idinfo['hd'] != GSUITE_DOMAIN_NAME:
        #     raise ValueError('Wrong hosted domain.')
    
        # ID token is valid. Get the user's Google Account ID from the decoded token.
        userid = idinfo['sub']
    except ValueError:
        # Invalid token
        pass
    

    verify_oauth2_token 函数会验证 JWT 签名、aud 声明和 exp 声明。您还必须通过检查 verify_oauth2_token 返回的对象来验证 hd 声明(如果适用)。如果多个客户端访问后端服务器,则还需要手动验证 aud 声明。

  3. 确认令牌的有效性后,您可以使用 Google ID 令牌中的信息将您网站的帐号状态关联起来:

    • 未注册用户:您可以显示一个注册界面,以便用户根据需要提供额外的个人资料信息。它还允许用户以静默方式创建新帐号和已登录的用户会话。

    • 网站中已存在的现有帐号:您可以显示一个网页,供最终用户输入密码并将旧版帐号与其 Google 凭据相关联。这将确认用户有权访问现有帐号。

    • 回访联合用户:您可以让用户以静默方式登录。