使用服務帳戶進行驗證

事前準備

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

設定驗證

若要以服務帳戶進行驗證:

  1. 將以下內容新增至 @Api 或方法註解:

    • authenticators 參數新增到註解,並設為 {EspAuthenticator.class} 值。
    • 新增包含 @ApiIssuerissuers 參數。
    • 新增包含設為服務帳戶核發單位和目標對象之 @ApiIssuerAudienceissuerAudiences 參數。

    例如:

    @Api(
        name = "echo",
        version = "v1",
        authenticators = {EspAuthenticator.class},
        issuers = {
            @ApiIssuer(
                name = "serviceAccount",
                issuer = "YOUR_SERVICE_ACCOUNT_EMAIL",
                jwksUri = "https://www.googleapis.com/robot/v1/metadata/x509/YOUR_SERVICE_ACCOUNT_EMAIL")
        },
        issuerAudiences = {
            @ApiIssuerAudience(name = "serviceAccount", audiences = "YOUR_AUDIENCE")
        })
    
    • echo 替換為您的 API 名稱。
    • v1 替換為您的 API 版本。
    • YOUR_SERVICE_ACCOUNT_EMAIL 替換為您的服務帳戶電子郵件地址。
    • YOUR_AUDIENCE 替換為呼叫服務傳送的 aud 欄位值。
  2. 在 API 的實作程式碼中匯入 Users

    import com.google.api.server.spi.auth.common.User;
    
  3. 在要檢查正確驗證的每種 API 方法中,檢查有效的 User 並在發現無效時擲回例外狀況,此範例方法定義如下所示:

    @ApiMethod(httpMethod = ApiMethod.HttpMethod.GET)
    public Email getUserEmail(User user) throws UnauthorizedException {
      if (user == null) {
        throw new UnauthorizedException("Invalid credentials");
      }
    
      Email response = new Email();
      response.setEmail(user.getEmail());
      return response;
    }
    
  4. 部署 API。當您新增新用戶端時,需要重新部署 API。