Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically send JWT token collected in previous request in Postman

I'm creating REST API (Symfony 4, FOS Rest bundle) and for testing I'm using Postman app. Problem is that at login request I get JWT token and later, in every other request I have to pass it back as part of Authorization header, as Bearer token. And since this token changes with every login I have to manually copy/paste token value after every login (when token expires).

Can that be avoided somehow and done automatically?

like image 279
MilanG Avatar asked Dec 23 '22 00:12

MilanG


1 Answers

First, after successful authorization - login call returned the JWT token it has to be stored into some variable. When editing login request, there is a "Tests" tab. Here we can put JavaScript code that will be executed after request is executed, so we will enter the code like this there:

var jsonData = JSON.parse(responseBody);
if(jsonData.token) {
    pm.globals.set("jwt-token", jsonData.token);
}

Or, shorter version, as @Danny Dainton suggested:

pm.globals.set("jwt-token", pm.response.json().token)

We are collecting response and storing "token" value to global variable called "jwt-token".

If you use older version of Postman this code should look a bit different - storing variable should look like:

postman.setEnvironmentVariable("jwt-token", jsonData.token); 

(Here storing as environmental variable vs. global variable in example above - both types should work. Use what you need).

So now, token value will be stored. Then we have to use it with other requests. Edit all other request that must pass JWT token. Go to "Authorization" tab, select "Bearer Token" authorization type and for value just enter {{jwt-token}} .

Again if you are using older version of Postman and don't have that "Bearer Token" type go to "Headers" tab instead, add new header with key "Authorization" and for it's value set Bearer {{jwt-token}}

That's it. Now you have to execute login request only once and JWT token will automatically be used in all other request.

And if you face some issue, you can use console to print debug info. Add in you code i.e.:

console.log(jsonData.token);

And from main menu go to View -> Show Postman Console to open console window where will you get console.log output.

like image 182
MilanG Avatar answered Dec 26 '22 06:12

MilanG