Having previously worked on projects which used session auth I was very happy that in my postman request all I had to do was send a login request, and postman was intelligent enough to use that session in subsequent requests.
Now I am working on projects with JWT auth and I was looking for a way to achieve the same effect without having to send the login request and copy/paste the token in the response into my next api request! I’ll share how I achieved this below.
Setting up the environment
If you don’t already have a Postman environment set up, you can follow my basic set up steps here: https://paulreaney.medium.com/how-to-set-up-postman-environments-ff5eeafb11f5
Add the ‘token’ environment variable
Open up ‘Manage environment’ in the top right
Click on the name of your environment, then add a variable called TOKEN, with any initial value as shown here:
Set the value of the token variable
I will assume you already have a login request that returns a JWT in the response like this:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
}
Now, while you have the login request tab open go to the ‘Tests’ tab of the login request and add the following code:
var jsonData = pm.response.json();
pm.environment.set("TOKEN", jsonData.token);
This will check the response of the login request and store the token value in the TOKEN environment variable. The token in jsonData.token will need renamed according to the naming of the token property in your api response.
Example:
After sending the login request you can check the token was populated by clicking the environment ‘quick look’ button:
Using the token
Now we just need to use the environment variable in each request that needs auth. You can do this by open the tab for the request you want to add the token to. Open the ‘Authorization’ tab, select ‘Bearer Token’ from the dropdown on the left and insert the token variable into the ‘Token’ input box on the right:
That’s it! You should now be able to send your requests as normal now and when the token expires you simply need to run another login request to re-populate the TOKEN environment variable.
Let me know of your Postman tips and tricks in the comments. Thanks!