-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
sign.ts
44 lines (41 loc) · 1.48 KB
/
sign.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
import { CompactSign } from '../jws/compact/sign.ts'
import { JWTInvalid } from '../util/errors.ts'
import type { JWTHeaderParameters, KeyLike, SignOptions } from '../types.d.ts'
import { encoder } from '../lib/buffer_utils.ts'
import { ProduceJWT } from './produce.ts'
/**
* The SignJWT class is used to build and sign Compact JWS formatted JSON Web Tokens.
*
*/
export class SignJWT extends ProduceJWT {
private _protectedHeader!: JWTHeaderParameters
/**
* Sets the JWS Protected Header on the SignJWT object.
*
* @param protectedHeader JWS Protected Header. Must contain an "alg" (JWS Algorithm) property.
*/
setProtectedHeader(protectedHeader: JWTHeaderParameters) {
this._protectedHeader = protectedHeader
return this
}
/**
* Signs and returns the JWT.
*
* @param key Private Key or Secret to sign the JWT with. See
* {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
* @param options JWT Sign options.
*/
async sign(key: KeyLike | Uint8Array, options?: SignOptions): Promise<string> {
const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)))
sig.setProtectedHeader(this._protectedHeader)
if (
Array.isArray(this._protectedHeader?.crit) &&
this._protectedHeader.crit.includes('b64') &&
// @ts-expect-error
this._protectedHeader.b64 === false
) {
throw new JWTInvalid('JWTs MUST NOT use unencoded payload')
}
return sig.sign(key, options)
}
}