This repository has been archived by the owner on Jan 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenx.js
56 lines (50 loc) · 1.56 KB
/
tokenx.js
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
const { Issuer } = require('openid-client');
let tokenxClient;
async function initTokenX() {
const tokenxIssuer = await Issuer.discover(process.env.TOKEN_X_WELL_KNOWN_URL);
tokenxClient = new tokenxIssuer.Client(
{
client_id: process.env.TOKEN_X_CLIENT_ID,
token_endpoint_auth_method: 'private_key_jwt',
},
{
keys: [JSON.parse(process.env.TOKEN_X_PRIVATE_JWK)],
}
);
}
async function getTokenXToken(token, additionalClaims) {
let tokenSet;
try {
tokenSet = await tokenxClient?.grant(
{
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
subject_token_type: 'urn:ietf:params:oauth:token-type:jwt',
audience: process.env.API_TOKENX_AUDIENCE,
subject_token: token,
},
additionalClaims
);
} catch (err) {
console.error('Noe gikk galt ved exchange token', err);
}
return tokenSet;
}
async function exchangeToken(token) {
if (!token) {
// Brukeren er ikke autorisert
return;
}
const additionalClaims = {
clientAssertionPayload: {
nbf: Math.floor(Date.now() / 1000),
// TokenX only allows a single audience
aud: [tokenxClient?.issuer.metadata.token_endpoint],
},
};
return await getTokenXToken(token, additionalClaims);
}
module.exports = {
initTokenX,
exchangeToken,
};