How to access oauth2 access token in a pre-request script?

Your question may already have an answer on the community forum. Please search for related topics, and then read through the guidelines before creating a new topic.

Here’s an outline with best practices for making your inquiry.

My question:
Hello, I’m using this process to get Oauth2 token: https://learning.postman.com/docs/sending-requests/authorization/#requesting-an-oauth-20-token and it’s working like a charm, unfortunately it seems there is no way to persist this token into a variable or getting access to it through a Postman function.

Details (like screenshots):

How I found the problem:
I’m trying to use the “pm.sendRequest” feature in the “Pre-request script” section, prior to retrieve data & use it into my main request. I need to authenticate with my oauth2 access token with the pm.sendRequest feature to get the data from the endpoint I need to reach.

I’ve already tried:
Getting variables from all scopes, from request.headers but it’s empty in pre-request script, also as a query, but automated query params are not found then in pre-request script.

1 Like

The following is an OAuth example authenticating against Microsoft.

pm.test("Check for collectionVariables", function () {
    let vars = ['clientId', 'clientSecret', 'tenantId', 'username', 'password', 'scope'];
    vars.forEach(function (item, index, array) {
        console.log(item, index);
        pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.undefined;
        pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.empty; 
    });

    if (!pm.collectionVariables.get("bearerToken") || Date.now() > new Date(pm.collectionVariables.get("bearerTokenExpiresOn") * 1000)) {
        pm.sendRequest({
            url: 'https://login.microsoftonline.com/' + pm.collectionVariables.get("tenantId") + '/oauth2/v2.0/token',
            method: 'POST',
            header: 'Content-Type: application/x-www-form-urlencoded',
            body: {
                mode: 'urlencoded',
                urlencoded: [
                    { key: "client_id", value: pm.collectionVariables.get("clientId"), disabled: false },
                    { key: "scope", value: pm.collectionVariables.get("scope"), disabled: false },
                    { key: "username", value: pm.collectionVariables.get("username"), disabled: false },
                    { key: "password", value: pm.collectionVariables.get("password"), disabled: false },                    
                    { key: "client_secret", value: pm.collectionVariables.get("clientSecret"), disabled: false },
                    { key: "grant_type", value: "password", disabled: false },
                ]
            }
        }, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                pm.test("Status code is 200", () => {
                    pm.expect(res).to.have.status(200);
                });
                let resJson = res.json();
                pm.collectionVariables.set("bearerTokenExpiresOn", resJson.expires_in);
                pm.collectionVariables.set("bearerToken", resJson.id_token);
            }
        });
    }
});

Thanks for this custom solution, I was hoping being able to rely on the native feature OAuth 2.0 just got easier: introducing token refresh and ID token support | Postman Blog at least for get & refresh the oauth2 access token and not a 100% custom solution… But maybe I will give up in the end if there’s no way to use native Postman feature at the time.

The “ugly” solution I’ve found so far is by executing this “placebo” request if I encounter any error with my other request:

If someone has a smarter/proper solution, feel free to share it :wink:

1 Like