Automate JWT token retrieval with Postman

Automate JWT token retrieval with Postman

Introduction

When I discover a new REST API, I usually like to explore it before I start to code against it. I do so by poking around to get a feeling of what it has to offer and usually start off by skimming through the documentation & examining the Swagger UI (if available). Then, at some point, I switch over to my tool of choice, which is Postman.

Now for OAuth 2.0 protected APIs it is rather time-consuming and inefficient having to request a token from the Azure AD endpoint manually, store it somewhere, and then setting the authorization header by pasting in the token.

We are going to automate this steps with postman's pre-request script feature.

"But, hey wait...", you say, "...then, why don't we just use the built-in OAuth 2.0 authorization mechanism that Postman provides out of the box?"

Because the current postman version (v8.3.1 as of writing) doesn't provide an automatic token refresh mechanism. And we'd like to ensure, that we are always calling with a fresh and valid token.

So long story short. This post demonstrates how the retrieval of an access token can be automated with Postman before sending an HTTP request.

For the sake of this demonstration, we are going to call the Microsoft Graph API with a system identity (see OAuth 2.0 client credential flow).

Please note, that Microsoft provides a web application called Graph Explorer that provides a more comfortable way to explore its API then demonstrated in this article here.

High-Level Steps

  1. Create an Azure app registration
  2. Prepare Postman
  3. Call API

1. Create Azure App Registration

  1. Create a new app registration, leave the redirect URI empty and name it e.g. Microsoft-Graph-Postman-Client. Make a note of the application id, after clicking Register.

2. Then create a client secret and copy it somewhere.

3. Grant your application some permissions of type Application I took User.Read.All here for demo purposes. Make sure the permission type is not Delegated as we are going to call with a system identity, remeber? 😉

4. Grant admin consent and make sure the status indicates the green check-sign

2. Prepare Postman

  1. Create a collection and give it a descriptive name
  2. Set the Authorization section of your collection to Bearer Token and the token field to the variable reference {{access_token}}

3. Now this is what you came for. Paste the following JavaScript into the Pre-request Script section of your collection.

const postRequest = {
  url: pm.collectionVariables.get("token_endpoint"),
  method: "post",
  header: {
    "Content-Type": "application/x-www-form-urlencoded",
  },
  body: {
    mode: "urlencoded",
    urlencoded: [
      {
        key: "grant_type",
        value: "client_credentials",
        disabled: false,
      },
      {
        key: "scope",
        value: pm.collectionVariables.get("scope"),
        disabled: false,
      },
      {
        key: "client_id",
        value: pm.collectionVariables.get("client_id"),
        disabled: false,
      },
      {
        key: "client_secret",
        value: pm.collectionVariables.get("client_secret"),
        disabled: false,
      },
    ],
  },
};

pm.sendRequest(postRequest, (error, response) => {
  if (error) {
    console.log(error);
  } else {
    pm.collectionVariables.set("access_token", response.json().access_token);
  }
});
Postman's JavaScript API exposes most of its functionality via the pm object. It provides a sendRequest() method that we are going to use to request and store an access token before making our final HTTP call to Microsoft's Graph API.

4. Create the following variables in the corresponding section of your collection. This is where the script expects its input parameters (pm.collectionVariables.get())

Key Value
client_id <your_client_id>
client_secret <your_client_secret>
token_endpoint https://login.microsoftonline.com/<your_tenant_id>/oauth2/v2.0/token
scope https://graph.microsoft.com/.default

Now that everything is in place, let's give it a shot 🤩

3. Call API

  1. Create a new request underneath your collection and make sure the Authorization section is set to Inherit auth from parent.
In the example I am requesting user details by specifying an email address. You won't be able to use https://graph.microsoft.com/v1.0/me in this scenario as we are calling with a system identity and not a user identity!

2. After clicking the send button you should get presented with an HTTP 200 and some user details.

Have a close look at the Console section of the screenshot from above. You should see two requests there, where the first one was issued by our pre-request script coming from the collection.

If you feel curious you might want to further examine the access token in use and paste it into a token debugger like https://jwt.ms.

Conclusion

As we have seen, Postman provides some nice scripting features that makes a developers life easier.

The nice thing about the proposed solution is that it allows us to add (almost) any Microsoft Graph calls to the collection without having to worry about authorization - as long as your app has the necessary app permissions.

Beautiful, isn't it 😎 That is it for today. In case you have any questions or feedback, please leave them in the comment field bellow or drop me a message.

Happy Hacking, Matthias 😀

Further reading

Microsoft Graph documentation
Microsoft Graph provides a unified programmability model that you can use to build apps for organizations and consumers that interact with the data of millions of users. You can use the Microsoft Graph REST APIs to access data in Azure Active Directory, Office 365 services, Enterprise Mobility and S…
Azure REST API reference documentation
Reference documentation for Azure REST APIs including their supported operations, request URI parameters and request bodies, responses, and object definitions.
Using variables
Scripting in Postman
Writing pre-request scripts
Graph Explorer - Microsoft Graph
The Microsoft Graph explorer is a tool that lets you make requests and see responses against the Microsoft Graph