Luis Sérgio
Luis Sérgio

Reputation: 649

How to open a JWT Token on Postman to put one of the claims value on a variable

To create a especific test on my application using Postman, after login and get the JWT token, I need to get a especific claim value to use in a variable in another POST on Postman.

Is that possible without develop a API to do it?

Thanks

Upvotes: 3

Views: 3618

Answers (3)

axetroll
axetroll

Reputation: 319

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.token);

Follow the: https://blog.postman.com/extracting-data-from-responses-and-chaining-requests/

Upvotes: 1

Scott
Scott

Reputation: 428

Here is a simple function to do that.

let jsonData = pm.response.json();
// use whatever key in the response contains the jwt you want to look into.  This example is using access_token
let jwtContents = jwt_decode(jsonData.access_token);

// Now you can set a postman variable with the value of a claim in the JWT
pm.variable.set("someClaim", jwtContents.payload.someClaim);

function jwt_decode(jwt) {
    var parts = jwt.split('.'); // header, payload, signature
    let tokenContents={};
    tokenContents.header = JSON.parse(atob(parts[0]));
    tokenContents.payload = JSON.parse(atob(parts[1]));
    tokenContents.signature = atob(parts[2]);

    // this just lets you see the jwt contents in the postman console.
    console.log("Token Contents:\n" + JSON.stringify(tokenContents, null, 2));

    return tokenContents;
}

The signature bit is still useless in this example, so you can not validate it with this, but it still addresses your question.

Upvotes: 4

R. Wright
R. Wright

Reputation: 1035

I've created a request in Postman that 'logs in' and, then, the tests section of the response contains the following

  var data = JSON.parse(responseBody);
  postman.clearGlobalVariable("access_token");
  postman.setGlobalVariable("access_token", data.access_token);

This puts the access token in a global variable so you can use it anywhere. If you're looking to read something from the JWT's claim, it's a bit more complicated.Check out how to add a library at https://github.com/postmanlabs/postman-app-support/issues/1180#issuecomment-115375864. I'd use the JWT decode library - https://github.com/auth0/jwt-decode .

Upvotes: -1

Related Questions