How to Store Token in Collection Variable

Hello,

I used to store the Auth Token in a global variable. Then, I moved it to a collection variable. A couple of weeks later, it stopped working. The auth service works, and I can copy and paste the token and use it. I just cannot find a way to store its value anymore.

Don’t know where my code stopped working.

{
    "auth": {
        "transID": "123456789",
        "message": {
            "id": "SUCCESS",
            "value": "Auth Succeed."
        },
        "token": "eyJraWQiOiJ[...]GdWpTd",
        "user": {
            "name": "CodyBanks",
            "uniqueId": "123456"
        }
    }
}


const jsonResponse = pm.response.json();
pm.collectionVariables.set("colToken", jsonResponse.Token);
console.log(jsonResponse.Token);
console.log("colToken = " + pm.collectionVariables.get("colToken"));

Console:
image

1 Like

The token key\value pair is under the auth object.

So it would be

console.log(jsonResponse.auth.Token);

I am experiencing the exact same issue. In the first request I retrieve an access token and store it in a variable. In the next request I add it as an “Authorization” header like “Bearer {{token}}”. This used to be working a week ago. Now it does not.

I am doing something like:

const response = pm.response.json();
pm.collectionVariables.set(“token”, response.access_token);

I also tried pm.variables.set. Also not working anymore

@davidhessling

Do you have an example response to your first request? To ensure its the same issue.

The original poster in this thread is targeting the token incorrectly, so that is the reason it’s not setting the collection variable.

Console log the token, to ensure its being targeted correctly before you try and set the collection variable.

console.log(response.access_token);

Thanks, guys, for your replies.

I ended up using Global variables. Not what I wanted, but good enough for my needs.

var jsonData = JSON.parse(responseBody);
pm.globals.set("BearerToken", jsonData.authResponse.token);