Michał Herman
Michał Herman

Reputation: 3587

Postman - JWT authentication using key file

I am trying to use Postman to test API developed on Google Cloud Platform: App Engine behind an API endpoint.
I have the key file in the JSON format:

{
  "type": "service_account",
  "project_id": "[[my_project_name]]",
  "private_key_id": "[[private_key_id]]",
  "private_key": "-----BEGIN PRIVATE KEY-----\n[[private_key]]\n-----END PRIVATE KEY-----\n",
  "client_email": "[[service_account_email]]",
  "client_id": "",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/[[service_account_email]]"
}

And I am able to retrieve access token using python code:

import time
import google.auth.crypt
import google.auth.jwt

sa_keyfile='[[path_to_the_api_key_file]]'
sa_email='[[service_account_email]]'
audience='[[my_api_url]]'
expiry_length=3600
now = int(time.time())
payload = {
    'iat': now,
    "exp": now + expiry_length,
    'iss': sa_email,
    'aud':  audience,
    'sub': sa_email,
    'email': sa_email
}

signer = google.auth.crypt.RSASigner.from_service_account_file(sa_keyfile)
jwt = google.auth.jwt.encode(signer, payload)

print(jwt)

If I setup in Postman OAuth 2.0 as authentication method and paste obtained JWT as Access Token then request is working just fine.

I would like to move whole JWT token operation into the Postman, without need to invoke Python code in advance. I tried to use Get New Access Token from Postman, but neither option supports JSON key file.
Is it possible to get JWT token from JSON key file using Postman only?

Upvotes: 2

Views: 8118

Answers (3)

Julian Mehnle
Julian Mehnle

Reputation: 313

After several hours of research, I found Denis Loginov's solution here: https://gist.github.com/dinvlad/425a072c8d23c1895e9d345b67909af0

It merely requires copying the code into your Postman collection's Pre-request Script field and configuring a few variables in your Postman environment.

I made this minor modification to update the Google API token service A make the scopes configurable via an environment variable as well:

--- pre_request.js.orig 2021-12-01 00:54:19.000000000 +0000
+++ pre_request.js  2021-12-01 00:56:24.000000000 +0000
@@ -22,13 +22,8 @@
 const ENV_TOKEN_EXPIRES_AT = 'tokenExpiresAt';
 const ENV_ACCESS_TOKEN = 'accessToken';
+const ENV_SCOPE = 'scope';

 const JS_RSA_SIGN_SRC = 'https://kjur.github.io/jsrsasign/jsrsasign-latest-all-min.js';
-const GOOGLE_OAUTH = 'https://www.googleapis.com/oauth2/v4/token';
-
-// add/remove your own scopes as needed
-const SCOPES = [
-    'https://www.googleapis.com/auth/userinfo.email',
-    'https://www.googleapis.com/auth/userinfo.profile',
-];
+const GOOGLE_OAUTH = 'https://oauth2.googleapis.com/token';

 const EXPIRES_MARGIN = 300; // seconds before expiration
@@ -74,5 +69,5 @@
             aud: GOOGLE_OAUTH,
             iss: client_email,
-            scope: SCOPES.join(' '),
+            scope: getEnv(ENV_SCOPE),
             iat,
             exp,

(My version on gist.github.com has some additional environment variables renamed because I prefer snake_case.)

Then set the following variables in your Postman environment:

  • serviceAccountKey (or service_account_key): insert your entire service account credentials JSON file, e.g.:
    {
      "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
      "auth_uri": "https://accounts.google.com/o/oauth2/auth",
      "client_email": "[email protected]",
      "client_id": "12345678901234567890",
      "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/service-account%40project-id.iam.gserviceaccount.com",
      "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEv...Fn9tg==\n-----END PRIVATE KEY-----\n",
      "private_key_id": "b0a...68b",
      "project_id": "project-id",
      "token_uri": "https://oauth2.googleapis.com/token",
      "type": "service_account"
    }
    
  • scope: a space-separated list of Google API scopes, e.g.:
    "https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.metadata"
    

Then run your requests.

Upvotes: 0

Jose V
Jose V

Reputation: 1496

You can try authenticating with Oauth making HTTP requests with Postman. The process would be the following:

  • Create a JSON Web Token yourself which includes a header, a claim set, and a signature. (The signature would require the private key from the service account key.json file)
  • Then request an access token from the Google OAuth 2.0 Authorization Server.
  • Afterwards get the access token from the JSON response that the
    Authorization Server returns.

It is explained in this link.

I think it can be done. Either way, I don't see this as a practical solution if it has to be done frequently.

Upvotes: 0

Maulik Parmar
Maulik Parmar

Reputation: 645

There are several ways to authorize users in GCP. Essentially and google's preferred way is to use key pairs to sign a request and send it to google for applications authenticity and authorize JWT related to context. While there are many options explaining how to do it server side, you need to be aware that these credentials actually allow you to access platform itself. This is essentially oAuth workflow and JWT you can get different sources have different scopes which in turns allows you to call endpoints related to them.

For postman you follow simple oAuth Workflow mentioned in docs which is straight forward Creating client IDs

Of course you need to implement serverside parts to call platform API's as they should not be exposed directly, hence extra security is given to obtain signed requests while getting platform tokens.

If you want to authorize end users this is the right guide : Authenticating users Same guide has other options on how to authorize other 'types' f application.

Assuming you are using OpenApi Specs as its standard way to access RESTFUL apis. Google has extensive documentation on using specific authentication provider for using their services.

Choosing an Authentication Method

Each methods have their pros & cons and select most suitable method that use JWT with proper privileges.

Other Documentation can be found here Cloud Endpoints documentation

Upvotes: 1

Related Questions