I love using Postman but it is a pain having to remember to enter a valid Bearer Token. The following is a Javascript pre-request I’ve used to automate the process.
Background
I’m using Auth0 for auth. My app consists of a Vue.js SPA and a .NET Core API.
Pretty much every endpoint in my API requires authentication. As I write each endpoint in my API I’m writing a Postman request so I can test it.
I have a Postman request to Auth0 to request a token.
To date I’ve been manually entering that token whenever I wanted to use an API endpoint. As you can imagine, this isn’t effective.
I just want my requests to always use a valid bearer token!

Step 1 – Create some variables
We to create two variables:
- Current bearer token
- Expiry date of the above token
You need to think about the scope of the variables. They can be anywhere from a global (across any test you’ve got) to the individual test. Checkout this article about scope in Postman.
I’m choosing to create my variables relative to the collection.
- Went to Ben’s API
- Clicked the three dots to open the menu
- Clicked Edit
- Let’s jump straight into the Variables tab and create our two variables which I’ve called currentAccessToken and accessTokenExpiry
Step 2 – the Pre-request Script
I went into Pre-request Scripts and wrote a script that does one of three things:
- If the token or expiry date is missing I get a fresh token and set the value
- If both variables are set but the expiry date is in the past I get a fresh token
- If there is a token AND it’s valid (it’s only good for 24 hours) then do nothing
Here’s the code
A few things to note:
- I put some console.log statements as Postman has a console and logging is always a good thing
- I did put all my secrets in this script. I’m not crazy about that but Postman doesn’t have a solution for secrets management. I’m going to try and use a test account in Auth0 to mitigate any issues
- You cannot call another Postman request from a script. That would have been really useful so instead I ended up writing this
- You
couldshould write some Tests under the test tab to confirm the token is set, it’s valid, etc. I haven’t yet got around to that
Step 3 – Authorization Setup
In the Authorization tab I set the
- Type to Bearer Token
- Token to {{currentAccessToken}}. This is the token we created and set via the pre-request script
Step 4 – Use the token!
For all your API requests do the following
- Go into the Authorization tab
- Under Type select Inherit auth from parent
You’re done!
But wait there’s more – Console and View the variables
In the top right-hand corner there is an eye icon. If you click it you can see the current state of all your variables. You can also click Edit and change the contents.
In the bottom-left corner is a console from which you can view all the logs you’ve written. I found it useful for debugging.
You can also use it to confirm that the pre-request script runs before each of your individual tests in your collection.
HI Ben,
How should I proceed to generate the OAuth2.0 token automatically that will be input to other test cases ?
LikeLike
I don’t know. Never used them. Could be something similar where you call a method(s) to get the value, which then gets save / used. Overall, the mechanism of writing a pre-request script could be the same but how you’d get it and populate it is something you’ll have to determine.
LikeLike
Hi Nagesh. Was wondering if you were able to figure it out(for oauth2)? I’m facing the problem. Thanks a lot!
LikeLike
Hi Nagesh, were you able to for OAuth2.0?
LikeLike
Sorry, I don’t know off hand
LikeLike
Nice! You are amazing I have found that very helpful. Thanks for sharing.
LikeLike
Nice! I’ve taken this and slightly changed it to use Lodash and Momentjs but it’s been really useful! I think I migh write a short post about the changes that I made. Thank you for sharing.
LikeLike
Hi Ben,
Thanks for such nice explanation.
Actually I am using basic auth for authorization and it’s a get request.
So how should I pass my user name and password with GET request.
I tried some technique, but didnt get proper solution.
Regards,
Rajnish
LikeLike
If it’s basic auth then it’s really easy. You don’t need this fancy system. You need to create two variables, for your username and password, and in your get request you pass those variables. In the top right of Postman you can create environments. In there you can definitely those two variables. Note that it would mean they’re just static but I assume that would be fine. Also, it would mean Postman would store that password so be careful about rhat
LikeLike
I’ve been using postman for years…
But, this is so much simpler:
https://github.com/eykrehbein/strest/blob/master/README.md
And the tests can be read when browsing the tests on GitHub.
Ever try to version control postman tests? It’s a mess.
LikeLike
That looks really. Thanks for sharing this! I agree, Postman is terrible for testing. Tried to use it, personally and at work, and it was pure frustration. About anything else is better
LikeLiked by 1 person
Very useful article!
I have been generating the token manually all the time but now it’s automated 😊
Thanks!
LikeLike
Works perfectly for me. Just what I needed.
Thanks
LikeLike
Nice explanation, thanks for putting together very clear instructions and examples.
LikeLike
Well explained. Have a question though. What if I have to add multiple headers while requesting tokens from OAuth.
const echoPostRequest = {
url: ‘https://.auth0.com/oauth/token’,
method: ‘POST’,
header: ‘Content-Type:application/json’,(How to add Authorization here?)
body: {
mode: ‘application/json’,
raw: JSON.stringify(
{
client_id:”,
client_secret:”,
audience:”,
grant_type:’client_credentials’
})
}
};
LikeLike
According to the postman sandbox docs, header: should accept an array of header strings.
LikeLike
I have a question regarding the authentication key. I am kinda new to api testing and trying to automate this bearer token.
So when I hit POST request with my user credential In response I will get the user information and in Headers I get authorization key as Set-Authentication : key .
How can I get key from here and pass it to pre- script. I tried following your solution but it’s taking response body into consideration. appreciate your help.
Thanks
LikeLike
Hi,
for some reason your code didn’t work for me. I had to change the body in this way:
body: {
mode: ‘urlencoded’,
urlencoded: [
{key: “grant_type”, value: “client_credentials”, disabled: false},
{key: “client_id”, value: “”, disabled: false},
{key: “client_secret”, value: “”, disabled: false},
{key: “resource”, value: “”, disabled: false}
]
}
This works for me.
Thanks!
LikeLike
Can we Generate the bearer token in postman?
LikeLike
Hey Ben,
What if the Authorization request is POST and the Authorization using Basic Auth sign. How can we refer them in the Pre-req part of the API
LikeLike
Hi! Just wanted to give you a big thanks for putting this guide together. No more constantly regenerating and pasting tokens! You’ve saved us all a lot of time and hassle.
LikeLike
thanks. this was helpful and a lot better than hitting the auth point manually
LikeLike
Thanks, wish I had found a week ago ; )
LikeLike
Hi,
Thanks for sharing this code I managed to get it working by changing the mode from application/json to raw for the body, see below for example:
“body”: {
“mode”: ‘raw’,
/Philip
LikeLike
This really helped speed up with regards to the Access Token. However it seems that I have an issue with the accessTokenExpiry in the script as it’s always reported as being missing ‘Token or expiry date are missing’.
Not sure if it’s because I got the format wrong, but then again it doesn’t do too much harm with getting a new Access Token each time.
LikeLike
Judging by the source code, it looks like body.mode will default to “raw” when you use “application/json”: http://www.postmanlabs.com/postman-collection/collection_request-body.js.html
I think body.mode is only supposed to be one of these: raw, formdata, urlencoded, file
LikeLike