# Scripting Token Management

**URL:** <https://community.postman.com/t/scripting-token-management/42949>\
**Category:** Help Hub\
**Created:** [January 17, 2023, 7:07am UTC](https://community.postman.com/t/scripting-token-management/42949 "2023-01-17T07:07:15Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![ktarayao](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/ktarayao/32/14481_2.png) [@ktarayao](https://community.postman.com/u/ktarayao)\
**Post date:** [January 17, 2023, 7:07am UTC](https://community.postman.com/t/scripting-token-management/42949/1 "2023-01-17T07:07:15Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![maddythedeveloper](https://avatars.discourse-cdn.com/v4/letter/m/9f8e36/32.png) [@maddythedeveloper](https://community.postman.com/u/maddythedeveloper)\
**Post date:** [January 17, 2023, 9:48am UTC](https://community.postman.com/t/scripting-token-management/42949/2 "2023-01-17T09:48:58Z")

</div>

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](https://www.npmjs.com/package/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.

---

<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 17, 2023, 11:38am UTC](https://community.postman.com/t/scripting-token-management/42949/3 "2023-01-17T11:38:37Z")

</div>

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

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

```

---

<div class="post-metadata">

**Author:** ![ktarayao](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/ktarayao/32/14481_2.png) [@ktarayao](https://community.postman.com/u/ktarayao)\
**Post date:** [January 18, 2023, 8:19am UTC](https://community.postman.com/t/scripting-token-management/42949/4 "2023-01-18T08:19:09Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![ktarayao](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/ktarayao/32/14481_2.png) [@ktarayao](https://community.postman.com/u/ktarayao)\
**Post date:** [January 20, 2023, 6:27am UTC](https://community.postman.com/t/scripting-token-management/42949/5 "2023-01-20T06:27:07Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![ktarayao](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/ktarayao/32/14481_2.png) [@ktarayao](https://community.postman.com/u/ktarayao)\
**Post date:** [January 20, 2023, 6:28am UTC](https://community.postman.com/t/scripting-token-management/42949/6 "2023-01-20T06:28:24Z")

</div>

Also, found this that was very helpful: [How to Automate OAuth2 Token Renewal in Postman | by Allen Helton | Medium](https://allenheltondev.medium.com/how-to-automate-oauth2-token-renewal-in-postman-864420d381a0)
