0

我正在尝试找出一种方法来创建 JWT 并使用服务帐户的私钥对其进行签名,并将签名的 JWT 在请求中发送到 Google API 端点。我已经搜索到有许多可用于 Java 和 Python 的库,但有可用于 PHP 的库吗?

将需要遵循 Google 的 Cloud Endpoints 标准在服务之间进行身份验证。下面是一个例子,说明我们如何访问 java,我想在 PHP 中完成?

 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 'expiraryLength' 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);
  GoogleCredential cred = GoogleCredential.fromStream(stream);
  RSAPrivateKey key = (RSAPrivateKey) cred.getServiceAccountPrivateKey();
  Algorithm algorithm = Algorithm.RSA256(null, key);
  return token.sign(algorithm);
}
4

1 回答 1

0

使用 PHP 向 Google Endpoints 创建经过身份验证的请求

对于 PHP 似乎不是一个好的解决方案,因为 Google 的云文档没有提供,您可以在此处看到。

尽管如此,有一些关于如何通过 JWT 的客户端在 Cloud Endpoints 中使用 PHP 的文档,您可以在此处看到,也可以在此处看到。

如果这些都不符合您的需要,您始终可以使用自定义方法对用户进行身份验证。如您所知,要对用户进行身份验证,客户端应用程序必须在 HTTP 请求的授权标头中向后端 API 发送 JSON Web 令牌 (JWT)。

因此,您可以使用可扩展服务代理 (ESP)

可扩展服务代理 (ESP) 代表您的 API 验证令牌,因此您无需在 API 中添加任何代码来处理身份验证。但是,您确实需要配置 OpenAPI 文档以支持您选择的身份验证方法。

您可以在此处查看如何为用户实现自定义方法身份验证。.

最后,如果您有兴趣,我会链接一些您可以与 Cloud Endpoints 服务一起使用的其他身份验证方法,以防上述方法都不符合您的需求。

我希望它有所帮助。

于 2020-01-02T14:26:00.473 回答