Dealing with requests that require authentication in Postman
In Postman, go to the request that does the login, then click on the Scripts tab.
Click on Post-response then add this code:
// Get the token from the Authorization header
var authHeader = pm.response.headers.get("Authorization");
// Check if header exists and starts with "Bearer "
if (authHeader && authHeader.startsWith("Bearer ")) {
// Extract the token (remove "Bearer " prefix)
var token = authHeader.substring(7);
// Save token to your environment
pm.environment.set("authToken", token);
console.log("Token successfully extracted and saved");
} else {
console.log("Authorization header not found or not in expected format");
}
This script creates an environment variable in Postman named authToken and sets the value to the jwt token that is sent in the Authorization header.
Click on the collection, that has all the requests to the API.
Click the Authorization tab
Select Bearer Token from the Auth Type dropdown
Paste this into the Token textbox: {{authToken}}
Click the Save button to save the changes.
In order to get the token be applied to all requests in the collection, you may have to click on the collection, then you should see an 'Environment' dropdown in the top right corner of the Postman window. Change this to New Envirnoment. You can change the environment name to whatever you want, but be sure that it is selected from the dropdown when you are making requests.
Now, whenever you send the login request, the token will be applied to all other requests in the collection.
You could also add this script to your logout request, and it will set the environment variable to undefined:
pm.environment.set("authToken", undefined);