使用服务账号进行身份验证

前提条件

本页面假定您已经完成以下操作:

配置身份验证

要使用服务账号进行身份验证,请执行以下操作:

  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。