Using JWT to authenticate and authorize requests in Postman
Tags: postman, api, jwt, node
Published: 2018-11-28 01:52:54

---
title: Using JWT to authenticate and authorize requests in Postman
published: true
description: How to use JSON Web Tokens (JWT) to authenticate and authorize requests in Postman
canonical_url: https://medium.com/postman-engineering/tuck-in-your-apis-safe-and-sound-with-these-guiding-principles-for-api-security-cd69f71c291e
tags: postman, api, jwt, node
cover_image: https://i.imgur.com/5RWNlFj.jpg
---

As you get started developing ironclad APIs, let’s take a look at how we can [use Postman to authorize our requests](https://learning.getpostman.com/docs/postman/sending_api_requests/authorization). In this example, we’ll use JSON Web Tokens to secure and access our API.

## What is JWT?
[JSON Web Token](https://jwt.io/) (JWT) is an [open standard](https://tools.ietf.org/html/rfc7519) for securely transmitting information between parties as a JSON object. It’s pronounced _jot_, or as our Dutch friends would say, _[yaywaytay](https://news.ycombinator.com/item?id=14293602)_.

JWT is commonly used for authorization. JWTs can be signed using a secret or a public/private key pair. Once a user is logged in, each subsequent request will require the JWT, allowing the user to access routes, services, and resources that are permitted with that token.

![using jwts](https://thepracticaldev.s3.amazonaws.com/i/zxloj1qn8j2iu5qy2ymd.png)

## Set up an API with JWT authentication
Let’s use this [example Node.js API](https://github.com/auth0-blog/nodejs-jwt-authentication-sample) from Auth0 that supports username and password authentication with JWTs and has endpoints that return Chuck Norris phrases. If you already have an API that you’re working on, you can skip this step.

For this example, make sure you have [Node.js](https://nodejs.org/en/download/) and the [npm](https://www.npmjs.com/package/download) package manager installed on your machine. Get started by cloning the repository, install the dependencies with `npm install`, and then start your server locally with `node.server.js`.

![run your server locally](https://thepracticaldev.s3.amazonaws.com/i/73bb7oc2s8va9tpq41bw.png)

Click the *Run in Postman* button at the bottom of the [README file](https://github.com/auth0-blog/nodejs-jwt-authentication-sample) to import the sample Postman collection into the Postman app. If you’re working off your own API, substitute your endpoints for the example included in this Postman collection.

The first request in the collection is a POST request to create user. If you already have a user, use the second request in the collection to create a new session. In both cases, you will see the access token included in the JSON response object.

![POST request to create a session
](https://thepracticaldev.s3.amazonaws.com/i/3hhdpices8idp0ocs30b.png)

## Save the JWT as a variable
You _could_ copy the access token from the response to use in your next request, but it’s tedious to do it for every request you want to authorize.

Instead, let’s save the JWT as a variable so that we can reuse the token over and over again in future requests. Create a new [environment](https://learning.getpostman.com/docs/postman/environments_and_globals/manage_environments#creating-a-new-environment). Under the Tests tab, save the access token [as an environment variable](https://learning.getpostman.com/docs/postman/scripts/test_examples) with `pm.environment.set()`, and re-run the request.

![Save the access token as an environment variable under the Tests tab](https://thepracticaldev.s3.amazonaws.com/i/m21g6tkqnjzv42nvp2mz.png)

Under the Quick Look icon, we can see that our JWT is saved as an environment variable. Now we can use our token in subsequent requests.

![JWT saved as an environment variable](https://thepracticaldev.s3.amazonaws.com/i/lkducwng1cd47ijxwbof.png)

## Add JWT to headers in Postman
There are 2 ways to send your JWT to authorize your requests in Postman: adding a header or using an authorization helper.

#### Option 1: add an authorization header
The first option is to add a header. Under the Headers tab, add a key called `Authorization` with the value `Bearer <your-jwt-token>`. Use the double curly brace syntax to swap in your token’s variable value.

If your authorization accepts a custom syntax, you can manually tweak the prefix here (e.g. `Token <your-access-token>` instead of `Bearer <your-access-token`).

![Option 1: add a header](https://thepracticaldev.s3.amazonaws.com/i/3hhbq5mk5khwobwg2ymh.png)

#### Option 2: use an authorization helper
The second option is to use an authorization helper. Under the Authorization tab, select the Bearer Token authorization type. Use the double curly brace syntax to swap in your token’s variable value.

![Option 2: use an Authorization helper](https://thepracticaldev.s3.amazonaws.com/i/1nye3act6m1qqwk2i7ju.png)

Click the orange Preview Request button to see a temporary header has been added under the Headers tab. This temporary header is not saved with your request or collection.

![Option 2: generates temporary headers](https://thepracticaldev.s3.amazonaws.com/i/wavc0bjb8f6f2vzljt1u.png)

**What’s the difference between these 2 approaches?** The approach you use should depend on how you’re planning to use it.

#### Option 1: add an authorization header
* User can tweak the prefix (e.g. `Token <your-access-token>` instead of `Bearer <your-access-token>`).
* Authorization header is displayed explicitly in the [API documentation](https://learning.getpostman.com/docs/postman/api_documentation/intro_to_api_documentation).
* With both of these options, you can share the request and collection with your teammates. Header is saved with the request and collection under the `header` property.

#### Option 2: use an authorization helper
* Can set authorization at the collection-, folder-, or request-level. Easy to set up the same authorization method for every request inside the collection or folder.
* With both of these options, you can share the request and collection with your teammates. Authorization is saved under the `auth` property.

## Scripts to check token expiration
JWT tokens don’t live forever. After a specified period of time, they expire and you will need to retrieve a fresh one.

Once again, there are 2 approaches for checking the expiration of your JWT. The approach you use choose will depend on your specific circumstances.

#### Option 1: Separate request at the beginning of the collection
This option is ideal if you’re working with a small collection that runs quickly, or you have a long-lived token that is not likely to expire by the end of the [collection run](https://learning.getpostman.com/docs/postman/collection_runs/intro_to_collection_runs). In this case, create an initial request at the beginning of the collection to retrieve and store the token. You can use the same token value throughout the remainder of your collection run.

#### Option 2: Pre-request script to run before each request

![Check for token expiration before sending your request](https://thepracticaldev.s3.amazonaws.com/i/pcq25va5ekykkxspd3tv.png)

This option is good if you’re working with a large collection that might take a while to run, or you have a short-lived token that could expire soon. In this case, add some logic in a [pre-request script](https://learning.getpostman.com/docs/postman/scripts/pre_request_scripts) to check if the current token is expired. If the token is expired, get a fresh one (e.g. using [`pm.sendRequest()`](https://learning.getpostman.com/docs/postman/scripts/postman_sandbox_api_reference/#pmsendrequest)) and then reset your new token’s time to live. With this approach, remember that you can use a collection- or folder-level script to run this check prior to every request in the collection or folder.

## Sessions to keep stuff private
Say that you saved your JWT as a Postman environment variable, and you shared the environment with your teammates because you’re collaborating on a project. Can you keep stuff private, so that your teammates don’t have access to it?

Yes, you can!

[Sessions](http://blog.getpostman.com/2018/08/09/sessions-faq/) are an additional layer within the Postman app that stores variable values locally. By default, sessions do not sync with Postman servers. Changes captured in the individual session remain local to your Postman instance, unless you explicitly sync to the cloud.

Go to your Settings, and toggle off “Automatically persist variable values”.

![Under your Settings, toggle off “Automatically persist variable values”](https://thepracticaldev.s3.amazonaws.com/i/85tpcwp6o8vyzlwqfyv6.png)

Now when you send a request and set a variable, the CURRENT VALUE is populated. You can think of this as a value that’s stored in a local session.

![Current values are stored in the local session](https://thepracticaldev.s3.amazonaws.com/i/lcuu3w9oudyfmujz5rlo.png)

If you want to share this value with your teammates or sync it to the Postman servers, this requires another step to to explicitly sync to the cloud. To sync all of your Current Values to the Initial Values, click Persist All. To sync only a single Current Value to the Initial Value, copy and paste the value from the 3rd column to the second column.

![Persist your local changes and sync to the cloud](https://thepracticaldev.s3.amazonaws.com/i/1fn2extkwaphx67ochyq.png)

Session variables allow you to reuse data and keep it secure while working in a collaborative environment. They allow you more granular control over syncing to the server or sharing information with your teammates. Learn more about [sessions](http://blog.getpostman.com/2018/08/09/sessions-faq/) or watch [a video about working with sessions](https://youtu.be/JcSZtVwH69w).

---

Want to tuck in your APIs safe and sound with other guiding principles for API security?

**Read the full article on the [Postman Engineering blog](https://medium.com/postman-engineering/tuck-in-your-apis-safe-and-sound-with-these-guiding-principles-for-api-security-cd69f71c291e).**