/
get-token-with-auth0
64 lines (52 loc) · 2.37 KB
/
get-token-with-auth0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
function parseJwt(token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
};
const loginRequest = {
url: pm.environment.get("auth0_endpoint") + '/oauth/token',
method: 'POST',
header: 'Content-Type: application/json',
body: {
mode: 'application/json',
raw: JSON.stringify({
"grant_type": pm.environment.get("grant_type"),
"client_id": pm.environment.get("client_id"),
"client_secret": pm.environment.get("client_secret"),
"username": pm.environment.get("username"),
"password": pm.environment.get("password"),
"scope": pm.environment.get("scope"),
"audience": pm.environment.get("audience")
})
}
};
if (!pm.environment.get('access_token_expiry') || !pm.environment.get('access_token') || (pm.environment.get('access_token_expiry') <= (new Date()).getTime())) {
console.log('Token is expired');
pm.sendRequest(loginRequest, function (err, response) {
if (err) {
console.log(err);
throw 'auth0 login fail';
}
var data = response.json();
if (response.code === 200) {
console.log('Status 200');
pm.environment.set("access_token", data.access_token);
pm.environment.set("refresh_token", data.refresh_token);
pm.environment.set("id_token", data.id_token);
//console.log("access_token = " + data.access_token);
var de_token = parseJwt(data.access_token);
console.log("de_token = " + JSON.stringify(de_token));
if (de_token['http://xrspace.account/properties']['username']) {
pm.environment.set("jwt_username", de_token['http://xrspace.account/properties']['username']);
}
if (de_token['http://xrspace.account/properties']['nickname']) {
pm.environment.set("jwt_nickname", de_token['http://xrspace.account/properties']['nickname']);
}
pm.environment.set("jwt_user_id", de_token['sub']);
pm.environment.set("access_token_expiry", de_token['exp'] + "000");
}
});
}