@@ -4,66 +4,48 @@ title: "createJWT()"
4
4
5
5
# ` createJWT() `
6
6
7
- Creates a new JWT. Claims are not included by default and must by defined with ` options ` .
7
+ Creates a new JWT. The algorithm is based on the header .
8
8
9
9
## Definition
10
10
11
11
``` ts
12
- // $ JWTAlgorithm=/reference/jwt/JWTAlgorithm
13
- // $ TimeSpan=/reference/main/TimeSpan
14
- function createJWT(
15
- algorithm : $$JWTAlgorithm ,
16
- key : Uint8Array ,
17
- payloadClaims : Record <any , any >,
18
- options ? : {
19
- headers? : Record <any , any >;
20
- expiresIn? : $$TimeSpan ;
21
- issuer? : string ;
22
- subject? : string ;
23
- audiences? : string [];
24
- notBefore? : Date ;
25
- includeIssuedTimestamp? : boolean ;
26
- jwtId? : string ;
27
- }
28
- ): Promise <string >;
12
+ // $ JWTHeader=/reference/jwt/JWTHeader
13
+ // $ JWTPayload=/reference/jwt/JWTPayload
14
+ function createJWT(key : Uint8Array , header : $$JWTHeader , payload : $$JWTPayload ): Promise <string >;
29
15
```
30
16
31
17
### Parameters
32
18
33
- - ` algorithm `
34
19
- ` key ` : Secret key for HMAC, and private key for ECDSA and RSA
35
- - ` payloadClaims `
36
- - ` options ` :
37
- - ` headers ` : Custom headers
38
- - ` expiresIn ` : How long the JWT is valid for (for ` exp ` claim)
39
- - ` issuer ` : ` iss ` claim
40
- - ` subject ` : ` sub ` claim
41
- - ` audiences ` : ` aud ` claims
42
- - ` notBefore ` : ` nbf ` claim
43
- - ` includeIssuedTimestamp ` (default: ` false ` ): Set to ` true ` to include ` iat ` claim
44
- - ` jwtId ` : ` jti ` claim
20
+ - ` header `
21
+ - ` payload `
45
22
46
23
## Example
47
24
48
25
``` ts
49
- import { HMAC } from " oslo/crypto" ;
50
- import { createJWT , validateJWT , parseJWT } from " oslo/jwt" ;
51
- import { TimeSpan } from " oslo" ;
26
+ // $ HMAC=/reference/crypto/HMAC
27
+ // $ createJWTHeader=/reference/jwt/createJWTHeader
28
+ // $ createJWTPayload=/reference/jwt/createJWTHeader
29
+ import { $$HMAC } from " oslo/crypto" ;
30
+ import { createJWT , $$createJWTHeader , $$createJWTPayload } from " oslo/jwt" ;
31
+ import { $$TimeSpan } from " oslo" ;
52
32
53
- const secret = await new HMAC (" SHA-256" ).generateKey ();
33
+ const key = await new HMAC (" SHA-256" ).generateKey ();
54
34
55
- const payload = {
56
- message: " hello, world"
57
- };
35
+ const header = createJWTHeader (" HS256" );
58
36
59
- const jwt = await createJWT (" HS256" , secret , payload , {
60
- headers: {
61
- kid
62
- },
37
+ const basePayload = createJWTPayload ({
63
38
expiresIn: new TimeSpan (30 , " d" ),
64
39
issuer ,
65
40
subject ,
66
41
audiences ,
67
42
includeIssuedTimestamp: true
68
43
});
44
+
45
+ const payload = {
46
+ message: " hello, world" ,
47
+ ... basePayload
48
+ };
49
+
50
+ const jwt = await createJWT (key , header , payload );
69
51
```
0 commit comments