How to authenticate via JWT in Postman

Using Postman for API testing? Here's how to set up a simple authentication script to easily save that jwt for later use.

Disclaimer: Your Mileage May Vary. This depends on a specific implementation of JWT which stores the token in the payload. Not all implementations work this way (and I'd guess most don't).

What Is A JWT?

It's important to note that the returned token will be a three-part string comprised of header, payload, and signature, separated by periods, and base64encoded. In my case, the payload contained the original jwt token so it was relatively easy to save that token and send it on later requests. To do this, my solution has to grab the token by base64 decoding the token, parsing the payload JSON, and grabbing (and base64 decoding again) the token from the json. You will almost certainly have to modify this script to match your API.

Let's Go

  1. Create an environment for your API if you have not already.
  2. Set the HOST, PORT, USERNAME and PASSWORD in your “environment” screen by clicking the “gear” icon in the upper right of the Postman app. For security, these variables are never synced to the Postman server.
  3. Create a TOKEN variable, but leave it blank. This variable will contain the JWT after a successful login.

Now your environment is all set for a login and JWT token.

  1. Create a new Postman request.
  2. Set the url as http://{{HOST}}:{{PORT}}/myAuthEndpoint and the method to POST.
  3. In the Body pane, add username={{USERNAME}} and password={{PASSWORD}}
  4. Add the following script to the Tests pane of the request.
    In Postman, test scripts run after the request has completed. Do not use a "Pre-request script", it will not work!
    var token = pm.response.json()["jwt"];
    // Grab the payload and base64 decode that
    var payload = atob(token.split(".")[1]);
    // grab the original token from the json
    var originalToken = JSON.parse(payload).token;
    // and, save to a variable for later use
    pm.environment.set("TOKEN", atob(token));
  5. Click “Send” on the authService request. The TOKEN variable should now be set in the environment, which means that it can be used by any other request for authentication.

That's it! You can now use the {{TOKEN}} variable in the authorization of any Postman request which is using your environment.

October 25, 2018

« Trimming TAB Characters in MySQL - Writing an Int To Time Function for MySQL »