I’ve a simple set of calls to my application’s endpoints and occasionally use Postman to test them or to simply call and see what the results look like. However my calls all require authentication tokens.
The aim here is that when I require a authentication token I’ll call a local app which gets them for me and I want Postman to call my code to retrieve as accessToken which can be used by Postman for subsequent calls
Let’s set up Postman to use a variable named accessToken…
- Create a “Environments” environment or use Globals
- Add a variable named accessToken (you can name yours whatever you want). Do not supply initial or current values and leave types as default
- Go to your request and in the Authorization tab, select the auth method. I chose Bearer Token as that’s what my endpoint uses.
- In the token type {{accessToken}}
At this point we have a link between the variable accessToken and the value sent into the Bearer Token but we need to generate the token and set it’s value into the variable accessToken.
- Select the Scripts tab and Pre-request
- Add the following
try { const response = await pm.sendRequest({ url: "https://localhost:5000/gettoken", method: "GET" }); pm.environment.set("accessToken", response.text()); } catch (err) { console.error(err); }
Obviously the URL in the above script should be whatever your server is and in my case I return raw text (you could have it deserialize from JSON as well ofcourse).
That’s it – Send the request, Postman calls your service to get the token and assigns it to accessToken and your Postman request should be authenticated.