loading...

Automating requests in postman which require Authorization

karthickash profile image Karthick Srinivasan ・1 min read

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);
});

Discussion

pic
Editor guide
Collapse
mrxinu profile image
Steve Klassen (He/Him)

That's exceptionally cool. Thanks for sharing!

Collapse
karthickash profile image
Karthick Srinivasan Author

Glad it helped :)

Collapse
patarapolw profile image
Pacharapol Withayasakpunt

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.