Home > Mobile >  Generates a signed JSON Web Token using a Google API Service Account in nodejs
Generates a signed JSON Web Token using a Google API Service Account in nodejs

Time:10-07

I have express/nodejs api that communication with our java backend services (not google API's). I need pass a google JWT token to the api calls.

How do I Generates a signed JSON Web Token using a Google API Service Account. Most of example I see get an access-token or refresh.

Thanks for your help

CodePudding user response:

Have a look at JSON Web Tokens.

CodePudding user response:

In this example, this code in Java is used to generate a function that creates a JWT, then it signs it by using the private key file, and returns the signed JWT. You could use it in your own code.

/**
 * 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);
}

You can review Google’s documentation of authentication between services.

  • Related