In this article, I show how to set up postman collection to automatically include an authorization token when making requests to secured endpoints.
Firstly, I am assuming you have already created a collection. I created one called medium. Next, we proceed to edit this collection. This would take us to this part of postman.
We start our editing with the variables tab. We add a new variable called token. We plan on updating this variable automatically once a user is authenticated and a response token is sent back to us. This value is what would then be passed as value in the Bearer token.
For now, we just assign anyvalue as its initial value
Next, we head back to the Authorization tab and change the Type to Bearer Token. For the Token value, instead of simply placing a raw token we would rather input the collection variable we created earlier. We do this by the use of a double curly bracket on both sides of the token. This would make the value of Bearer Token always pick from the value in the token variable we created.
As you can see we are almost done with our implementation what remains for us to complete this would be to find a way of updating the value of the token variable once we have a new token.
Sample response data
For this example, we have an auth endpoint that authenticates and return a response with data in this format.
"message": "User sucessfully login",
We would need to pass this token value in the object returned in the header to other endpoints that are secured and require a token passed.
Set token in collection header
The Tests tab is where we would be adding our code snippet that would enable us to extract the token from the response and store it in the collection token variable.
To do that we send a post request with our body parameters to the endpoint to authenticate us.
All things set, we click the send button, this returns the data object and a status code of 200.
To check if our code snippets work, we head back to the collection variables to see the current value of token and wolla!
Test secured routes
To test this in other endpoints which are secured we need to do one last thing.
To have a single source of truth for the token, we set the Type in Authorization to Inherit auth from parent.
Now, this route and any other secured route in this collection always have the current token in its header whenever it sends a request. Cool right? Yeah!
Thats all there is to automating our token addition to our header requests. Not only did this save me some precious time but it was also fun implementing and very rewarding, lol.
Have a blast!