Change the name of the parameter called "access_token"

I have successfully setup an OAuth 2.0 authorization with the outcome that Postman has created a parameter called “access_token” with the token value.

Is there a way to change the parameter name to “token” as I need to append it to the end of my GET requests using the name “token”.

This works: https:://some.url/records?token=******

This does not work: https:://some.url/records?access_token=******

When I make a new request the parameter called “access_token” is greyed out and I want to change the name to “token”.

The OAuth 2.0 standard returns access_token, id_token or both.

I can’t see any options for setting the variable it creates to another name.

Sounds like you can’t use the authorization helpers (the authorization tab) for your request.

You can submit a feature request if this is needed.

You should however be able to setup a fully fledged request which you can parse the response, retrieve the token and give it whatever variable name you want.

The following is an example to see how this can be done.

const response = pm.response.json();
pm.environment.set("token", response.access_token); 

Or use sendRequest() in a pre-request script to do the same thing.

Either of these methods will give you more control over the returned token.

To get this solution to work, do I need to create a parameter or a variable that is called “token”? Furthermore, I am confused where I should place the code example that you provided? Ideally I would like this to work when authorizing and apply to any request within the colleciton.

To get this solution to work, do I need to create a parameter or a variable that is called “token”? Furthermore, I am confused where I should place the code example that you provided? Ideally I would like this to work when authorizing and apply to any request within the collection.

You need to create a variable called token. To use it in a request, you need to save it as a collection or environment variable (I recommend an environment variable).

If you want to work it with any request, then the best option is a pre-request script that checks the expiry date of the token.

The following is an example of authenticating to Azure Key Vault that you can use as a baseline.

if (!pm.environment.get("bearerToken") || currentDateTime > tokenExpiry) {
    pm.test("Pre-request check for Environment Variables", function () {
        let vars = ['client_id', 'scope', 'tenant_id', 'client_secret', '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("tenant_id") + '/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("client_id"), disabled: false },
                    { key: "scope", value: pm.environment.get("scope"), disabled: false },
                    { key: "client_secret", value: pm.environment.get("client_secret"), disabled: false },
                    { key: "grant_type", value: "client_credentials", 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);
                    let token = resJson.access_token;
                    // console.log(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);
                    // console.log(decoded);
                    let expiryDate = new Date(decoded.exp * 1000);
                    // console.log(expiryDate);

                    pm.environment.set("bearerToken", token);
                    pm.environment.set("bearerTokenExpiresOn", expiryDate);
                    // console.log("bearerTokenExpiresOn: " + pm.environment.get("bearerTokenExpiresOn"));
                });
            }
        });
    });
};

This is another example where the API also includes an expiry date, so you don’t need to pull apart the token to get the date.

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', 'testaccount_one_name', 'testaccount_one_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("testaccount_one_name"), disabled: false },
                    { key: "password", value: pm.environment.get("testaccount_one_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"));
                });
            }
        });
    });
};

You need to test the expiration as I found that API’s return vastly different date formats. Yours might be slightly different to the two examples shown above. The two example are both using Microsoft, but different services, and one service returns a date in the response, and the other does not (Hence you need to test that its actually working).

You need to update the request so it matches the authentication for your API. Client Credentials, Password, etc. This won’t work with API’s that use the authentication_code grant, as that requires browser\user interaction.

The above requires a base level understanding of JavaScript.

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