DEV Community

Karthick Srinivasan
Karthick Srinivasan

Posted on

Automating requests in postman which require Authorization

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);
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

mrxinu profile image
Steve Klassen (They/Them)

That's exceptionally cool. Thanks for sharing!

angrybuddha24 profile image
Karthick Srinivasan

Glad it helped :)

patarapolw profile image
Pacharapol Withayasakpunt • Edited

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.