Please enable Javascript to view the contents

Postman使用Test解析jwt验证claim

 ·  ☕ 1 分钟

重要

最重要的事: 通过postman的tests模块解析jwt,从而在Console查看claim的值。

配置

在请求access-token的请求中,添加Tests脚本。请求示例如下

1
2
3
4
5
6
7
curl --location --request POST 'https://sso.icos.city/auth/realms/icos/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'username=hexiang' \
--data-urlencode 'password=xxxxxx' \
--data-urlencode 'client_id=<client-id>' \
--data-urlencode 'client_secret=<client-secret>'

增加的Test脚本如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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;
}

Reference

Issue - 在Tests中解析jwt并显示claim

Stack Overflow - 在Tests中解析jwt并修改claim值

Stack Exchange - decoding-jwt-and-testing-results-in-postman

Postman 文档 - Write Tests

分享

Hex
作者
Hex
CloudNative Developer

目录