Search code examples
testingoauth-2.0postmanopenid-connect

Auto-Increment ID's for OAuth2.0 Access Tokens in Postman


I am trying to implement an auto-incrementing ID to append to my token name in order to differentiate better between tokens retrieved at different times.

I was able to get as far as figuring out to create a variable called tokenCount and autoincrement it in the tests tab using this code:

let tokenCount = pm.collectionVariables.get("tokenCount");
tokenCount++;
pm.collectionVariables.set("tokenCount", tokenCount);

However, this only increments when I send my request; not when I retrieve a new access token. Is there any way that I can run this code upon the access token retrieval instead?


Solution

  • The following is an example of a pre-request script that authenticates against Microsoft using OAuth 2.0.

    You will need to change the body to match the grant type you are using.

    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);
                        let tokenName = pm.environment.get("tokenName")
                        let tokenCount = pm.environment.get("tokenCount");
                        tokenCount++;
                        pm.environment.set(tokenName + tokenCount, resJson.id_token);
                        pm.environment.set("bearerTokenExpiresOn", Date.now() + resJson.expires_in * 1000);
                        pm.environment.set("tokenCount", tokenCount);
                        // console.log("bearerTokenExpiresOn: " + pm.environment.get("bearerTokenExpiresOn"));
                    });
                }
            });
        });
    };
    

    These are the added lines that deal with the auto-incrementing number.

    let tokenName = pm.environment.get("tokenName")
    let tokenCount = pm.environment.get("tokenCount");
    tokenCount++;
    pm.environment.set(tokenName + tokenCount, resJson.id_token);
    pm.environment.set("tokenCount", tokenCount);
    

    You will need Environment variables called tokenName and tokenCount. You will also need to initialise the tokenCount. For example 000.