Setting oauth access token from different response json prop

I was able to get oauth token from a client’s API using postman’s ‘Get New Access Token’ button, however the property names aren’t standard so postman didn’t automatically assign the response token data as access token.

Can I automatically run a script after this so that the access token is set from ‘accessToken’ or do I have to run a separate request to perform said script?
image

Hi @aviation-astronomer3. Welcome to the Postman Community Forum!

When you click the “Get New Access Token” button, Postman makes an authorization requests to an authorization server using credentials you specified. It then fetches your access and refresh token pair using the authorization grant gotten from the authorization request. All of this is done strictly following the laid down standard of the OAuth 2.0 Authorization framework. The OAuth 2.0 Authorization framework specifies that when an access token request is made, the access token response gotten should be in snake case (access_token, and refresh_token) see here.

Unfortunately, there isn’t a way to override this behavior in Postman when using the “Get New Access Token” button feature as it goes against the specification. However, if you make the authorization request yourself in a request, and you store the authorization grant in a Collection/Environment variable, you can chain another request to fetch the access and refresh tokens. Here, you will have full control over the structure, but will loose the auto-refresh tokens feature that comes with the “Get New Access Token” button.

Please let me know if you have any questions.

You can also use a pre-request script which will allow you more options with what you can do with the response.

You can also use the expiry dates so that you aren’t getting a new token each and every time.

Here is an example of authenticating to Microsoft that you can use as a starter for 10.

let currentDateTime = Date.now();
let tokenExpiry = pm.environment.get("bearerTokenExpiresOn")
// console.log("currentDateTime: " + currentDateTime);
// console.log("tokenExpiry: " + tokenExpiry);
if (!pm.environment.get("bearerToken") || currentDateTime > tokenExpiry) {
    pm.test("Pre-request check for Environment Variables", function () {
        let vars = ['clientId', 'clientSecret', 'tenantId', 'username', 'password', 'scope'];
        vars.forEach(function (item) {
            // console.log(item);
            pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.undefined;
            pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.empty;
        });
        pm.sendRequest({
            url: 'https://login.microsoftonline.com/' + pm.environment.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.environment.get("clientId"), disabled: false },
                    { key: "scope", value: pm.environment.get("scope"), disabled: false },
                    { key: "username", value: pm.environment.get("username"), disabled: false },
                    { key: "password", value: pm.environment.get("password"), disabled: false },
                    { key: "client_secret", value: pm.environment.get("clientSecret"), disabled: false },
                    { key: "grant_type", value: "password", disabled: false },
                ]
            }
        }, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                pm.test("Pre-request Microsoft login Status code is 200", () => {
                    pm.expect(res).to.have.status(200);
                    let resJson = res.json();
                    // console.log(resJson);
                    pm.environment.set("bearerToken", resJson.id_token);
                    pm.environment.set("bearerTokenExpiresOn", Date.now() + resJson.expires_in * 1000);
                    // console.log("bearerTokenExpiresOn: " + pm.environment.get("bearerTokenExpiresOn"));
                });
            }
        });
    });
};

The following example is where the API doesn’t specifically provide you with an expiry time. The details can usually still be retreived from the actual token.

let moment = require('moment');
let currentDateTime = moment(new Date()).format("YYYYMMDDHHmmss");
let tokenExpiry = moment(pm.environment.get("tokenExpiresOn")).format("YYYYMMDDHHmmss");
// console.log("currentDateTime: " + currentDateTime);
// console.log("tokenExpiry: " + tokenExpiry);

if (!pm.environment.get("JWT") || currentDateTime > tokenExpiry) {
    pm.test("Pre-request check for required Environment Variables", function () {
        let vars = ['username', 'password'];
        vars.forEach(function (item) {
            // console.log(item);
            pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.undefined;
            pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.empty;
        });
        pm.sendRequest({
            url: 'https://' + pm.environment.get("URL") + '/thirdparty-access/v1/authenticate',
            method: 'POST',
            header: 'Content-Type: application/json',
            body: {
                mode: 'raw',
                raw: JSON.stringify({ 'userName': pm.environment.get("username"), 'password': pm.environment.get("password") })
            }
        }, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                pm.test("Pre-request Authentication Status code is 200", () => {
                    pm.expect(res).to.have.status(200);
                    let resJson = res.json();
                    // console.log(resJson);
                    let token = resJson["id-token"]

                    function parseJwt(token) {
                        var base64Url = token.split('.')[1];
                        var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
                        var jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
                            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
                        }).join(''));

                        return JSON.parse(jsonPayload);
                    }

                    let decoded = parseJwt(token);
                    let expiryDate = new Date(decoded.exp * 1000);

                    pm.environment.set("tokenExpiresOn", expiryDate);
                    pm.environment.set("JWT", token);
                    // console.log("Token ExpiresOn: " + pm.environment.get("tokenExpiresOn"));
                    
                });
            }
        });
    });
};

Thank you @gbadebo-bello and @michaelderekjones for the detailed responses! Will see if the client could follow the standard, and perform one of the recommended scripts otherwise.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.