Scripting Token Management

I’m trying to write a pre-request script that will do 2 things:

  1. delete all expired tokens, and
  2. check to see if there is already a token that is not expired.
    I already know how to get a new token in a pre-request script, but don’t want to do that every time if I already have a good token.

I’ve spent a good deal of time searching and haven’t been able to find anything useful to help me script token management. Any nudge in the right direction would be appreciated.

If there is a request collection which has requests expecting token for an API call then:
Requests run in the same sequence as they are arranged.
First request’s pre-request script can get the token and store it in collection/global variable of postman.
Subsequent requests can use that variable to use valid token.
In order to validate token expiration, it needs to be decoded (Refer: jwt-decode ) and checked with expires claim.
Generally auth providers create token token with expiration claim. If your token is specific to the custom auth provider then jwt-decode might not work.

This is an example of authenticating against Microsoft that checks the current token to see if its expired before requesting a new one.

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);
            }
        });
    }
});

Just to clarify: what I am really asking is if there is a way to loop through the tokens in current collection that are saved under Collection → Authorization → Current Token → Token → Manage Tokens in the UI. If you click through to that menu, there is a button you can click to Delete Expired Tokens. Is there any way to call that function from a Pre-request Script?

I now see that there is a Auto-refresh token toggle on the Collection → Authorization page, but it doesn’t support Client Credential grant types, only Authorization Code grant types. Therefore, @michaelderekjones 's solution is the best. Thank you!

Also, found this that was very helpful: How to Automate OAuth2 Token Renewal in Postman | by Allen Helton | Medium