服務之間的驗證

除了驗證使用者,您可能也需要允許其他服務與 API 互動。雖然用戶端應用程式可以提供網路登入提示給使用者,請使用者提交其憑證,但還需要另一種方法來進行安全的服務對服務通訊。本頁面說明我們建議採用的服務間驗證實作方法,並提供程式碼範例。

總覽

為了識別傳送要求至您 API 的服務,需要使用服務帳戶。呼叫服務會使用服務帳戶的私密金鑰簽署安全的 JSON Web Token (JWT),並在要求中將已簽署的 JWT 傳送至 API。

在 API 和呼叫服務內進行服務對服務的驗證:

  1. 建立呼叫服務要使用的服務帳戶與金鑰。
  2. 在 Cloud Endpoints 服務的 OpenAPI 文件新增驗證支援。
  3. 將程式碼新增到呼叫服務,如此就會:

    • 建立 JWT 並以服務帳戶私密金鑰簽署。
    • 在要求中將已簽署的 JWT 傳送至 API。

ESP 會先驗證 JWT 中的宣告是否與 OpenAPI 文件中的設定相符,再將要求轉送至 API。ESP 不會檢查您在服務帳戶上授予的 Cloud Identity 權限。

必要條件

本頁假設您已具備以下條件:

使用金鑰建立服務帳戶

您會需要一個服務帳戶,這個服務帳戶需擁有呼叫服務用來簽署 JWT 的私密金鑰檔案。如果您有多個服務會向您的 API 發送要求,則可建立一個服務帳戶來代表所有的呼叫服務。如果您需要區別不同服務 (例如各服務具有的權限可能各不相同),就可以為每個呼叫服務建立服務帳戶和金鑰。

本節說明如何使用 Google Cloud 控制台和gcloud指令列工具,建立服務帳戶和私密金鑰檔案,並為服務帳戶指派服務帳戶權杖建立者角色。如要瞭解如何使用 API 執行這項工作,請參閱「建立及管理服務帳戶」。

如要建立服務帳戶和金鑰,請按照下列步驟操作:

Google Cloud 控制台

  1. 建立服務帳戶:

    1. 前往 Google Cloud 控制台的「Create service account」(建立服務帳戶) 頁面。

      前往「Create Service Account」(建立服務帳戶) 頁面

    2. 選取要使用的專案。

    3. 在 [Service account name] (服務帳戶名稱) 欄位中輸入一個名稱。

    4. (選用) 在「Service account description」(服務帳戶說明) 欄位中輸入說明。

    5. 點選「建立」。

    6. 按一下「完成」。

      請勿關閉瀏覽器視窗,後續步驟會用到。

  2. 建立服務帳戶金鑰:

    1. 在 Google Cloud 控制台中,點按您建立的服務帳戶電子郵件地址。
    2. 點按「Keys」(金鑰)。
    3. 依序點選「新增金鑰」和「建立新的金鑰」。
    4. 點選「建立」。系統會將含有服務帳戶私密金鑰的 JSON 檔案下載到您的電腦。
    5. 按一下 [關閉]。

gcloud

您可以在本機電腦上使用 Google Cloud CLI,或在 Cloud Shell 中執行下列指令。

  1. 設定 gcloud 的預設帳戶。如果您有多個帳戶,請務必選擇要使用的 Google Cloud 專案中的帳戶。

    gcloud auth login
    
  2. 顯示 Google Cloud 專案的專案 ID。

    gcloud projects list
    
  3. 設定預設專案。將 PROJECT_ID 替換為要使用的 Google Cloud 專案 ID。

    gcloud config set project PROJECT_ID
  4. 建立服務帳戶。將 SA_NAME 和 SA_DISPLAY_NAME 替換為您要使用的名稱和顯示名稱。

    gcloud iam service-accounts create SA_NAME \
      --display-name "SA_DISPLAY_NAME"
  5. 顯示剛剛建立的服務帳戶的電子郵件地址。

    gcloud iam service-accounts list
    
  6. 新增服務帳戶憑證建立者角色。將 SA_EMAIL_ADDRESS 替換成服務帳戶的電子郵件地址。

    gcloud projects add-iam-policy-binding PROJECT_ID \
      --member serviceAccount:SA_EMAIL_ADDRESS \
      --role roles/iam.serviceAccountTokenCreator
  7. 在目前使用的目錄中建立服務帳戶金鑰檔案。將 FILE_NAME 替換為您要用於金鑰檔案的名稱。根據預設,gcloud 指令會建立一個 JSON 檔案。

    gcloud iam service-accounts keys create FILE_NAME.json \
      --iam-account SA_EMAIL_ADDRESS

如要進一步瞭解上述指令,請參閱 gcloud 參考資料。

如需私密金鑰保護措施的相關資訊,請參閱管理憑證的最佳做法。

設定 API 以支援驗證

如要為呼叫閘道的服務啟用服務帳戶驗證,請修改 OpenAPI 文件中的安全性物件,讓 ESP 驗證已簽署 JWT 中的宣告。修改方式會因使用的 OpenAPI 規格版本而異。

OpenAPI 2.0

  1. 在 OpenAPI 規格中,將服務帳戶新增為核發者:
    securityDefinitions:
        DEFINITION_NAME:
          authorizationUrl: ""
          flow: "implicit"
          type: "oauth2"
          x-google-issuer: "SA_EMAIL_ADDRESS"
          x-google-jwks_uri: "https://www.googleapis.com/robot/v1/metadata/x509/SA_EMAIL_ADDRESS"
      
    • 將 DEFINITION_NAME 替換為用於識別這項安全性定義的字串。建議您將其替換為服務帳戶名稱,或可識別呼叫服務的名稱。
    • 將 SA_EMAIL_ADDRESS 替換為服務帳戶的電子郵件地址。
    • 您可以在 OpenAPI 規格中定義多個安全性定義,但每個定義都必須有不同的 x-google-issuer。如果您已為每個呼叫服務建立個別服務帳戶,則可為每個服務帳戶建立安全性定義,例如:
      securityDefinitions:
          service-1:
            authorizationUrl: ""
            flow: "implicit"
            type: "oauth2"
            x-google-issuer: "service-1@example-project-12345."
            x-google-jwks_uri: "https://www.googleapis.com/robot/v1/metadata/x509/service-1@example-project-12345."
          service-2:
            authorizationUrl: ""
            flow: "implicit"
            type: "oauth2"
            x-google-issuer: "service-2@example-project-12345."
            x-google-jwks_uri: "https://www.googleapis.com/robot/v1/metadata/x509/service-2@example-project-12345."
  2. 也可以將 x-google-audiences 新增至 securityDefinitions 區段。如未新增 x-google-audiences,ESP 會要求 JWT 中的 "aud" (目標對象) 宣告採用 https://SERVICE_NAME 格式,其中 SERVICE_NAME 是您在 OpenAPI 文件的 host 欄位中設定的 ESP 服務名稱。
  3. 在檔案的頂層 (不縮排或巢狀) 新增 security 區段,套用至整個 API,或在方法層級套用至特定方法。如果您在 API 層級和方法層級都使用 security 區段,方法層級的設定會覆寫 API 層級的設定。
    security:
      - DEFINITION_NAME: []
    • 將 DEFINITION_NAME 替換為您在「securityDefinitions」一節中使用的名稱。
    • 如果 securityDefinitions 區段中有多個定義,請在 security 區段中新增這些定義,例如:
      security:
        - service-1: []
        - service-2: []
  4. 部署更新後的 OpenAPI 規格。ESP 將要求轉送至 API 前,會先驗證:
    • 使用公開金鑰的 JWT 簽章,位於 OpenAPI 規格中 x-google-jwks_uri 欄位指定的 URI。
    • JWT 中的 "iss" (核發者) 宣告與 x-google-issuer 欄位中指定的值相符。
    • JWT 中的 "aud" (目標對象) 宣告包含 ESP 服務名稱,或與您在x-google-audiences欄位中指定的值相符。
    • 使用 "exp" (到期時間) 宣告,確認權杖未過期。

OpenAPI 3.x

  1. 在 OpenAPI 規格中,將服務帳戶新增為核發者:
    components:
      securitySchemes:
        SCHEME_NAME:
          type: oauth2
          flows:
           implicit:
             authorizationUrl: ""
             scopes: {}
          x-google-auth:
            issuer: SA_EMAIL_ADDRESS
            jwksUri: https://www.googleapis.com/robot/v1/metadata/x509/SA_EMAIL_ADDRESS
            audiences:
              - 848149964201.apps.googleusercontent.com
              - 841077041629.apps.googleusercontent.com
            jwtLocations:
              - header: Authorization
                valuePrefix: "Bearer "
    security:
      - SCHEME_NAME: []
    • 將 SCHEME_NAME 替換為用於識別此安全性配置的字串。建議您將其替換為服務帳戶名稱,或可識別呼叫服務的名稱。
    • 將 SA_EMAIL_ADDRESS 替換為服務帳戶的電子郵件地址。
    • 您可以在 OpenAPI 規格中定義多個安全性配置,但每個定義都必須有不同的 issuer。如果您已為每個呼叫服務建立個別服務帳戶,則可為每個服務帳戶建立安全性定義,例如:
      components:
        securitySchemes:
          service-1:
            type: oauth2
            flows:
             implicit:
               authorizationUrl: ""
               scopes: {}
            x-google-auth:
              issuer: "service-1@example-project-12345."
              jwksUri: https://www.googleapis.com/robot/v1/metadata/x509/service-1@example-project-12345.
              jwtLocations:
                - header: Authorization
                  valuePrefix: "Bearer "
          service-2:
            type: oauth2
            flows:
             implicit:
               authorizationUrl: ""
               scopes: {}
            x-google-auth:
              issuer: "service-2@example-project-12345."
              jwksUri: "https://www.googleapis.com/robot/v1/metadata/x509/service-2@example-project-12345."
              jwtLocations:
                - header: Authorization
                  valuePrefix: "Bearer "
  2. 也可以將 audiences 新增至 securitySchemes 區段。如未新增 audiences,ESP 會要求 JWT 中的 "aud" (目標對象) 宣告採用 https://SERVICE_NAME 格式,其中 SERVICE_NAME 是您在 OpenAPI 文件的 host 欄位中設定的 ESP 服務名稱。
  3. 在檔案的頂層 (不縮排或巢狀) 新增 security 區段,套用至整個 API,或在方法層級套用至特定方法。如果您在 API 層級和方法層級都使用 security 區段,方法層級的設定會覆寫 API 層級的設定。
    security:
      - SCHEME_NAME: []
    • 將 SCHEME_NAME 替換為您在「securitySchemes」一節中使用的名稱。
    • 如果 securitySchemes 區段中有多個定義,請在 security 區段中新增這些定義,例如:
      security:
        - service-1: []
        - service-2: []
  4. 部署更新後的 OpenAPI 規格。ESP 將要求轉送至 API 前,會先驗證:
    • 使用公開金鑰的 JWT 簽章,位於 OpenAPI 規格中 jwksUri 欄位指定的 URI。
    • JWT 中的 "iss" (核發者) 宣告與 issuer 欄位中指定的值相符。
    • JWT 中的 "aud" (目標對象) 宣告包含 ESP 服務名稱,或與您在audiences欄位中指定的值相符。
    • 使用 "exp" (到期時間) 宣告,確認權杖未過期。

向 Endpoints API 發出經過驗證的要求

為了發出經過驗證的要求,呼叫服務會傳送您在 OpenAPI 文件中指定的服務帳戶簽署的 JWT。呼叫服務必須:

  1. 建立一個 JWT,並以服務帳戶私密金鑰簽署。
  2. 在要求中將簽署的 JWT 傳送至 API。

以下程式碼範例示範了特定語言的這項程序。如要以其他語言發出已驗證的要求,請參閱 jwt.io,查看支援的程式庫清單。

  1. 在呼叫服務中,新增以下函式,並將以下參數傳送給函式:
    Java
    • saKeyfile:服務帳戶私密金鑰檔案的完整路徑。
    • saEmail:服務帳戶的電子郵件地址。
    • audience:如果已在 OpenAPI 文件中新增了 x-google-audiences 欄位,請將 audience 設定為您指定給 x-google-audiences 的其中一個值。或是將 audience 設定為 https://SERVICE_NAME,其中 SERVICE_NAME 是您的 Endpoints 服務名稱。
    • expiryLength:JWT 的到期時間,以秒為單位。
    Python
    • sa_keyfile:服務帳戶私密金鑰檔案的完整路徑。
    • sa_email:服務帳戶的電子郵件地址。
    • audience:如果已在 OpenAPI 文件中新增了 x-google-audiences 欄位,請將 audience 設定為您指定給 x-google-audiences 的其中一個值。或是將 audience 設定為 https://SERVICE_NAME,其中 SERVICE_NAME 是您的 Endpoints 服務名稱。
    • expiry_length:JWT 的到期時間,以秒為單位。
    Go
    • saKeyfile:服務帳戶私密金鑰檔案的完整路徑。
    • saEmail:服務帳戶的電子郵件地址。
    • audience:如果已在 OpenAPI 文件中新增了 x-google-audiences 欄位,請將 audience 設定為您指定給 x-google-audiences 的其中一個值。或是將 audience 設定為 https://SERVICE_NAME,其中 SERVICE_NAME 是您的 Endpoints 服務名稱。
    • expiryLength:JWT 的到期時間,以秒為單位。

    此函式會建立一個 JWT,並使用私密金鑰檔案來簽署 JWT,然後將已簽署的 JWT 傳回。

    Java
    /**
     * Generates a signed JSON Web Token using a Google API Service Account
     * utilizes com.auth0.jwt.
     */
    public static String generateJwt(final String saKeyfile, final String saEmail,
        final String audience, final int expiryLength)
        throws FileNotFoundException, IOException {
    
      Date now = new Date();
      Date expTime = new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(expiryLength));
    
      // Build the JWT payload
      JWTCreator.Builder token = JWT.create()
          .withIssuedAt(now)
          // Expires after 'expiryLength' seconds
          .withExpiresAt(expTime)
          // Must match 'issuer' in the security configuration in your
          // swagger spec (e.g. service account email)
          .withIssuer(saEmail)
          // Must be either your Endpoints service name, or match the value
          // specified as the 'x-google-audience' in the OpenAPI document
          .withAudience(audience)
          // Subject and email should match the service account's email
          .withSubject(saEmail)
          .withClaim("email", saEmail);
    
      // Sign the JWT with a service account
      FileInputStream stream = new FileInputStream(saKeyfile);
      ServiceAccountCredentials cred = ServiceAccountCredentials.fromStream(stream);
      RSAPrivateKey key = (RSAPrivateKey) cred.getPrivateKey();
      Algorithm algorithm = Algorithm.RSA256(null, key);
      return token.sign(algorithm);
    }
    Python
    def generate_jwt(
        sa_keyfile,
        sa_email="account@project-id.iam.gserviceaccount.com",
        audience="your-service-name",
        expiry_length=3600,
    ):
        """Generates a signed JSON Web Token using a Google API Service Account."""
    
        now = int(time.time())
    
        # build payload
        payload = {
            "iat": now,
            # expires after 'expiry_length' seconds.
            "exp": now + expiry_length,
            # iss must match 'issuer' in the security configuration in your
            # swagger spec (e.g. service account email). It can be any string.
            "iss": sa_email,
            # aud must be either your Endpoints service name, or match the value
            # specified as the 'x-google-audience' in the OpenAPI document.
            "aud": audience,
            # sub and email should match the service account's email address
            "sub": sa_email,
            "email": sa_email,
        }
    
        # sign with keyfile
        signer = google.auth.crypt.RSASigner.from_service_account_file(sa_keyfile)
        jwt = google.auth.jwt.encode(signer, payload)
    
        return jwt
    
    
    Go
    
    // generateJWT creates a signed JSON Web Token using a Google API Service Account.
    func generateJWT(saKeyfile, saEmail, audience string, expiryLength int64) (string, error) {
    	now := time.Now().Unix()
    
    	// Build the JWT payload.
    	jwt := &jws.ClaimSet{
    		Iat: now,
    		// expires after 'expiryLength' seconds.
    		Exp: now + expiryLength,
    		// Iss must match 'issuer' in the security configuration in your
    		// swagger spec (e.g. service account email). It can be any string.
    		Iss: saEmail,
    		// Aud must be either your Endpoints service name, or match the value
    		// specified as the 'x-google-audience' in the OpenAPI document.
    		Aud: audience,
    		// Sub and Email should match the service account's email address.
    		Sub:           saEmail,
    		PrivateClaims: map[string]interface{}{"email": saEmail},
    	}
    	jwsHeader := &jws.Header{
    		Algorithm: "RS256",
    		Typ:       "JWT",
    	}
    
    	// Extract the RSA private key from the service account keyfile.
    	sa, err := os.ReadFile(saKeyfile)
    	if err != nil {
    		return "", fmt.Errorf("could not read service account file: %w", err)
    	}
    	conf, err := google.JWTConfigFromJSON(sa)
    	if err != nil {
    		return "", fmt.Errorf("could not parse service account JSON: %w", err)
    	}
    	block, _ := pem.Decode(conf.PrivateKey)
    	parsedKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
    	if err != nil {
    		return "", fmt.Errorf("private key parse error: %w", err)
    	}
    	rsaKey, ok := parsedKey.(*rsa.PrivateKey)
    	// Sign the JWT with the service account's private key.
    	if !ok {
    		return "", errors.New("private key failed rsa.PrivateKey type assertion")
    	}
    	return jws.Encode(jwsHeader, jwt, rsaKey)
    }
    
  2. 在呼叫服務中,新增下列函式,以在要求中使用 Authorization: Bearer 標頭傳送已簽署的 JWT 給 API:
    Java
    /**
     * Makes an authorized request to the endpoint.
     */
    public static String makeJwtRequest(final String signedJwt, final URL url)
        throws IOException, ProtocolException {
    
      HttpURLConnection con = (HttpURLConnection) url.openConnection();
      con.setRequestMethod("GET");
      con.setRequestProperty("Content-Type", "application/json");
      con.setRequestProperty("Authorization", "Bearer " + signedJwt);
    
      InputStreamReader reader = new InputStreamReader(con.getInputStream());
      BufferedReader buffReader = new BufferedReader(reader);
    
      String line;
      StringBuilder result = new StringBuilder();
      while ((line = buffReader.readLine()) != null) {
        result.append(line);
      }
      buffReader.close();
      return result.toString();
    }
    Python
    def make_jwt_request(signed_jwt, url="https://your-endpoint.com"):
        """Makes an authorized request to the endpoint"""
        headers = {
            "Authorization": "Bearer {}".format(signed_jwt.decode("utf-8")),
            "content-type": "application/json",
        }
        response = requests.get(url, headers=headers)
        print(response.status_code, response.content)
        response.raise_for_status()
    
    
    Go
    
    // makeJWTRequest sends an authorized request to your deployed endpoint.
    func makeJWTRequest(signedJWT, url string) (string, error) {
    	client := &http.Client{
    		Timeout: 10 * time.Second,
    	}
    
    	req, err := http.NewRequest("GET", url, nil)
    	if err != nil {
    		return "", fmt.Errorf("failed to create HTTP request: %w", err)
    	}
    	req.Header.Add("Authorization", "Bearer "+signedJWT)
    	req.Header.Add("content-type", "application/json")
    
    	response, err := client.Do(req)
    	if err != nil {
    		return "", fmt.Errorf("HTTP request failed: %w", err)
    	}
    	defer response.Body.Close()
    	responseData, err := io.ReadAll(response.Body)
    	if err != nil {
    		return "", fmt.Errorf("failed to parse HTTP response: %w", err)
    	}
    	return string(responseData), nil
    }
    

當您使用 JWT 傳送一項要求時,基於安全考量,建議您將驗證憑證放入 Authorization: Bearer 標頭之中。例如:

curl --request POST \
  --header "Authorization: Bearer ${TOKEN}" \
  "${ENDPOINTS_HOST}/echo"

其中 ENDPOINTS_HOST 和 TOKEN 是環境變數,分別包含 API 主機名稱和驗證權杖。

在 API 中接收驗證結果

ESP 通常會轉送收到的所有標頭。不過,如果後端位址是由 OpenAPI 規格中的 x-google-backend 或 gRPC 服務設定中的 BackendRule 指定,則會覆寫原始 Authorization 標頭。

ESP 會將 X-Endpoint-API-UserInfo 中的驗證結果傳送至後端 API。建議您使用這個標頭,而非原始 Authorization 標頭。這個標頭是 base64url 編碼 JSON 物件的字串。ESPv2 和 ESP 的 JSON 物件格式不同。如果是 ESPv2,JSON 物件就是原始 JWT 酬載。如果是 ESP,JSON 物件會使用不同的欄位名稱,並將原始 JWT 酬載放在 claims 欄位下方。如要進一步瞭解格式,請參閱「在後端服務中處理 JWT」。

後續步驟