Create a Google access_token using a Service Account

How it works?

In some scenarios, you might want to access Google Admin APIs from your applications. Accesing those APIs require either a consent of the Google Apps administrator or creating a Service Account and obtain a token programatically without interactive consent. This rule create such token based on a service account and put it under user.admin_access_token.

To create a service account go to Google API Console, create a new Client ID and choose Service Account

You will get the key that you would have to convert to PEM and remove the passphrase using this command

openssl pkcs12 -in yourkey.p12 -out yourkey.pem -nocerts -nodes

Login to Google Apps Admin and go to (Security -> Advanced Settings -> Manage OAuth Client Access) Enter

Enter the Client ID created on the previous step and the scope you want to allow access to.

  • KEY: the string representation of the key (open the PEM and replace enters with \n to make it one line).
  • GOOGLE_CLIENT_ID_EMAIL: this is the email address of the service account created (NOT the Client ID).
  • SCOPE: the scope you want access to. Full list of scopes
  • ADMIN_EMAIL: a user of your Google Apps domain that this rule would impersonate.

NOTE: the Google access_token will last 1 hour, so you will have to either force a re-login or use a refresh token to trigger a token refresh on Auth0 and hence the rule running again.

NOTE 2: you might want to be careful what scopes you ask for and where the access_token will be used. For instance, if used from a JavaScript application, a low-privilieged user might grab the token and do API calls that you wouldn't allow.

Here's the rule:

How do I use it?

Just create a new rule in the Auth0 dashboard, and copy the following code replacing the placeholders with the appropriate values.

What is a Rule?

A rule is arbitrary JavaScript code that can be used to extend Auth0s default behavior when authenticating a user. Enabled rules will be executed in the order shown below for all users and applications as the final step of theauthentication process.

Rules can be used to enrich and transform the user profile, deny access to specific users under certain conditions, retrieve information from external services and much more. To learn more about rules, see Auth doc Rules