0

I am trying to figure out a way to create a JWT and sign it with the service account's private key and Send the signed JWT in a request to the Google API Endpoint. I have search out there are numerous of the library available for Java and Python but is there any library available for PHP?

will need to follow Google’s Cloud Endpoints standard for authentication between services. Below there is an example of how we can access java, which I wanted to accomplish in 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);
}
Piyush Sharma
  • 591
  • 7
  • 9

1 Answers1

0

Using PHP to create authenticated request to an Google Endpoints

For PHP seems to not be a good solution since is not provided by the Google's Cloud documentation, as you can see here.

Nonetheless, there are some documentation regarding how you can use PHP within Cloud Endpoints via the JWT's client, as you can see here, and also here.

If neither of those fit your needs you can always use a custom method to authenticate users. As you know to authenticate a user, a client application must send a JSON Web Token (JWT) in the authorization header of the HTTP request to your backend API.

As a consequent, you could use the Extensible Service Proxy (ESP):

The Extensible Service Proxy (ESP) validates the token on behalf of your API, so you don't have to add any code in your API to process the authentication. However, you do need to configure your OpenAPI document to support your chosen authentication methods.

You could see how to implement custom method authentication for users here..

Finally, in case you are interested I link some other authentication methods that you could use with your Cloud Endpoints services in case none of the above fit your needs.

I hope it helps.