授權與驗證

實作要求訊息驗證,確保向 Google 發出的結帳和提交訂單要求皆來自 Google,並防止未經授權的第三方呼叫您的端點。

使用 JWT 進行訊息驗證

基於安全考量,凡是由訂購端對端伺服器發出的執行要求端點要求,Authorization 標頭中都會包含已簽署的 JSON Web Token (JWT)。權杖由共用授權服務產生,Google 和您的執行要求端點實作皆可呼叫該服務。

  1. Google 會使用授權服務和你的訂餐專案專案 ID 產生已簽署的 JWT。
  2. Google 會在每個要求的 Authorization 標頭中,將已簽署的權杖傳送至您的執行要求端點。
  3. 您的端點必須使用 Google 驗證程式庫對已簽署的憑證解碼。經過解碼的權杖含有專案 ID、核發者、到期時間和核發時間等詳細資料。請使用這項資料判斷要求的真實性。

如要實作專案要求驗證,請按照下列步驟操作:

  1. 從傳入要求的 Authorization 標頭擷取 JWT。
  2. 使用 Google 驗證程式庫將權杖解碼。
  3. 將權杖的 audience 設為您的專案 ID。
  4. 驗證權杖酬載中包含的核發者、專案 ID 和其他資訊是否正確。

Google 授權資料庫

如要驗證來自「排序端對端」的訊息,並產生網路服務傳送給 Google 的訊息授權碼,請使用您選擇的程式設計語言中的 Google 驗證程式庫:

下載其中一個程式庫,並加到網路服務實作程式碼中。

要求驗證範例

以下範例說明如何導入要求驗證:

Node.js

const auth = require('google-auth-library')
const authClient = new auth.OAuth2Client()

/**
 * Verifies that an incoming request came from Google.
 * @param {String} idToken - The ID token used to verify the request
 * (i.e. The value found in the Authorization header of an incoming request).
 * @param {String} audience - The expected audience of the request
 * (i.e. The project ID for your project).
 * @return {boolean} True if request came from Google, false otherwise.
 */
function isRequestFromGoogle(idToken, audience) {
  authClient.verifyIdToken({idToken, audience}, (err, info) => {
    return !(err || info['iss'] !== 'https://accounts.google.com')
  })
}
    

Python

from google.oauth2 import id_token
from google.auth.transport import requests

def isRequestFromGoogle(audience, token):
    """ Verifies that an incoming request came from Google.

    Args:
        audience (str): The expected audience of the request
                        (i.e. The project ID for your project)
        token (str): The ID token used to verify the request
                     (i.e. The value found in the Authorization
                     header of an incoming request)
    Returns:
        True if the request came from Google, False otherwise.
    """
    id_info = id_token.verify_oauth2_token(token, requests.Request(), audience)
    return id_info['iss'] == 'https://accounts.google.com'
    

Java

/**
 * Verifies that an incoming request came from Google.
 * @param audience The expected audience of the request
 *                 (i.e. The project ID for your project)
 * @param token The ID token used to verify the request
 *              (i.e. The value found in the Authorization
 *              header of an incoming request)
 * @return {@code true} if request is from Google, else {@code false}
 */
public boolean isRequestFromGoogle(String audience, String token) {
  GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier
      .Builder(transport, jsonFactory)
      .setAudience(Collections.singletonList(audience))
      .build();

  GoogleIdToken idToken = verifier.verify(token);
  if (idToken == null) return false;
  Payload payload = idToken.getPayload();
  String issuer = (String) payload.get("iss");
  return issuer.equals("https://accounts.google.com");
}