如何在邮递员上打开 JWT 令牌以将其中一个声明值放在变量上



要使用 Postman 在我的应用程序上创建特定测试,在登录并获取 JWT 令牌后,我需要获取一个特定声明值以在 Postman 上另一个 POST 中的变量中使用。

如果不开发 API 来做到这一点,这可能吗?

谢谢

这是一个简单的函数来做到这一点。

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

在本例中,签名位仍然无用,因此您无法用此签名位对其进行验证,但它仍然可以解决您的问题。

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

遵循: https://blog.postman.com/extracting-data-from-responses-and-chaining-requests/

我在 Postman 中创建了一个"登录"的请求,然后,响应的测试部分包含以下内容

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

这会将访问令牌放在全局变量中,以便您可以在任何地方使用它。如果你想从JWT的声明中读一些东西,那就有点复杂了。在 https://github.com/postmanlabs/postman-app-support/issues/1180#issuecomment-115375864 查看如何添加库。我会使用 JWT 解码库 - https://github.com/auth0/jwt-decode .

最新更新