Automatic JWT Token setup in Postman
January 19, 2023
• 3 min read
While working with APIs, we test them in an API Client, and the most popular client is Postman. If the API has an authentication system, we log in through an endpoint and collect a JWT (JSON web token). Then we can access protected routes by setting the token into the header. We can automate this manual process by using Postman's environment variables. Before that, let's take an idea about Postman's environment variables.
Postman's Environment Variables
If our API's Base URL is localhost:3000
, instead of writing this in every request, we can set this on an environment variable and use it like this {{URL}}/endpoint
. Later changing the variable, we can simply test the production version of the application.
Set an environment variable
Postman 👉 Environments 👉 Create new Environment 👉 Enter a name, a variable name, and the value for your environment.
I named the environment Todo Project
and set the variable name URL
& value localhost:3000
Then save and active the environment by clicking on the check icon. Now, we can access any route like this - {{URL}}/route
Set Token Automatically
Let' say, we have an endpoint named {{URL}}/user/login
which returns a token if we send valid credentials. And we have another endpoint named {{URL}}/todos
that requires authentication using the token.
So, here is the plan - we'll take the token from the response and set it on an environment variable. By doing this, we don't have to manually set it in every request the requires authentication.
In the {{URL}}/user/login
tab, go to the Tests tab and add these two lines of code -
const response = pm.response.json();
pm.environment.set('JWT_TOKEN', response.token);
This will take the token form response and set that on an environment variable named JWT_TOKEN
. Now, log in again with the credentials.
Now we have to variables in the Todo Project
environment.
- URL
- {{JWT_TOKEN}}
Access Private Endpoints
Remember? We have a route {{URL}}/todos
that requires token authentication. To access this route -
- Open a new postman tab
- Put this URL {{URL}}/todo
- Go to the Authorization tab
- Select type Bearer token
- On the right box just write the variable name which is JWT_TOKEN
You'll be able to access that route like this-
Now you can add authorization on any endpoint with two clicks like this. And the token will be updated automatically if you log in again.