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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With