# Setting oauth access token from different response json prop

**URL:** <https://community.postman.com/t/setting-oauth-access-token-from-different-response-json-prop/56380>\
**Category:** Help Hub\
**Tags:** oauth2\
**Created:** [January 9, 2024, 4:25pm UTC](https://community.postman.com/t/setting-oauth-access-token-from-different-response-json-prop/56380 "2024-01-09T16:25:18Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![aviation-astronomer3](https://avatars.discourse-cdn.com/v4/letter/a/7feea3/32.png) [@aviation-astronomer3](https://community.postman.com/u/aviation-astronomer3)\
**Post date:** [January 9, 2024, 4:25pm UTC](https://community.postman.com/t/setting-oauth-access-token-from-different-response-json-prop/56380/1 "2024-01-09T16:25:19Z")

</div>

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](https://us1.discourse-cdn.com/getpostman/original/3X/9/2/92c8fdf4d30d88b29f0e2f6747faddbbd6fb9c60.png)

---

<div class="post-metadata">

**Author:** ![gbadebo-bello](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/gbadebo-bello/32/12175_2.png) [@gbadebo-bello](https://community.postman.com/u/gbadebo-bello)\
**Post date:** [January 12, 2024, 8:18pm UTC](https://community.postman.com/t/setting-oauth-access-token-from-different-response-json-prop/56380/2 "2024-01-12T20:18:18Z")

</div>

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](https://datatracker.ietf.org/doc/html/rfc6749#section-4.2.2:~:text=Appendix%20B%3A-,access_token,-REQUIRED.%20%20The%20access).

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.

---

<div class="post-metadata">

**Author:** ![michaelderekjones](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/michaelderekjones/32/14819_2.png) [@michaelderekjones](https://community.postman.com/u/michaelderekjones)\
**Post date:** [January 13, 2024, 1:45pm UTC](https://community.postman.com/t/setting-oauth-access-token-from-different-response-json-prop/56380/3 "2024-01-13T13:45:21Z")

</div>

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.

```auto
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.

```auto
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"));
                    
                });
            }
        });
    });
};

```

---

<div class="post-metadata">

**Author:** ![aviation-astronomer3](https://avatars.discourse-cdn.com/v4/letter/a/7feea3/32.png) [@aviation-astronomer3](https://community.postman.com/u/aviation-astronomer3)\
**Post date:** [January 14, 2024, 1:34pm UTC](https://community.postman.com/t/setting-oauth-access-token-from-different-response-json-prop/56380/4 "2024-01-14T13:34:27Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/system/32/29796_2.png) [@system](https://community.postman.com/u/system)\
**Post date:** [February 13, 2024, 1:34pm UTC](https://community.postman.com/t/setting-oauth-access-token-from-different-response-json-prop/56380/5 "2024-02-13T13:34:55Z")

</div>

Closed on February 13, 2024, 1:34pm UTC

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