-
Notifications
You must be signed in to change notification settings - Fork 0
/
examples.ts
46 lines (38 loc) · 1.26 KB
/
examples.ts
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
import { JwkFactory } from '@dreamauth/jwk';
import { JwtDecoder, JwtFactory, JwtVerifier } from './src/index.js';
// You need a private JWK for JWT signing, and a public JWK for JWT
// verification. These would normally be generated ahead of time, and
// rotated occasionally.
const jwkFactory = new JwkFactory();
const { publicKey, privateKey } = await jwkFactory.createRSA('RS256');
//
// Create JWTs.
//
const jwtFactory = new JwtFactory('https://issuer.com', {
header: { foo: 'default header value' },
payload: { bar: 'default payload value' },
lifetime: 3600, // Default token lifetime in seconds.
});
// Create a JWT, signed with the private JWK.
const jwt = await jwtFactory.create(privateKey, {
header: { foo: 'override header value' },
payload: { bar: 'override payload value' },
lifetime: 1800, // Override token lifetime in seconds.
});
//
// Decode and verify the JWT.
//
const verifier = new JwtVerifier(['https://issuer.com'], {
loader: {
load: async (iss: string) => {
// Load all public JWKs for the given issuer.
return [publicKey];
},
},
});
const decoder = new JwtDecoder(verifier);
try {
const decoded = await decoder.decode(jwt);
} catch (error) {
// Errors are thrown when the JWT is malformed or fails verification.
}