If sending a request demands new authorization token each and every time, running the requests as a collection might be a little tricky.
Postman provides us an option to parameterize the access token generation process by adding a pre-request script and environment variables.
Parameterize the authorization at the collection level with the below code:
let tokenUrl = 'url';
let clientId = '<>';
let clientSecret = '<>';
let scope = '<>';
let getTokenRequest = {
method: 'POST',
url: tokenUrl,
auth: {
type: "basic",
basic: [
{ key: "username", value: username },
{ key: "password", value: password }
]
},
body: {
mode: 'urlencoded',
urlencoded: [
{ key: 'grant_type', value: 'username' },
{ key: 'scope', value: scope }
]
}
};
pm.sendRequest(getTokenRequest, (err, response) => {
let jsonResponse = response.json(),
newAccessToken = jsonResponse.access_token;
console.log({ err, jsonResponse, newAccessToken })
pm.globals.set('accessToken', newAccessToken);
pm.environment.set('accessToken', newAccessToken);
pm.variables.set('accessToken', newAccessToken);
});
Top comments (3)
That's exceptionally cool. Thanks for sharing!
Glad it helped :)
Actually, I use Swagger UI or Redoc, instead of Postman or Postwoman.
For some reasons, it is not talked about much in Express.js. But, it is fully supported in Fastify.