/
jwt.service.ts
175 lines (159 loc) 路 4.84 KB
/
jwt.service.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import { Inject, Injectable, Logger, Optional } from '@nestjs/common';
import * as jwt from 'jsonwebtoken';
import {
JwtModuleOptions,
JwtSecretRequestType,
JwtSignOptions,
JwtVerifyOptions
} from './interfaces';
import { JWT_MODULE_OPTIONS } from './jwt.constants';
@Injectable()
export class JwtService {
private readonly logger = new Logger('JwtService');
constructor(
@Optional()
@Inject(JWT_MODULE_OPTIONS)
private readonly options: JwtModuleOptions = {}
) {}
sign(
payload: string,
options?: Omit<JwtSignOptions, keyof jwt.SignOptions>
): string;
sign(payload: Buffer | object, options?: JwtSignOptions): string;
sign(payload: string | Buffer | object, options?: JwtSignOptions): string {
const signOptions = this.mergeJwtOptions(
{ ...options },
'signOptions'
) as jwt.SignOptions;
const secret = this.getSecretKey(
payload,
options,
'privateKey',
JwtSecretRequestType.SIGN
);
const allowedSignOptKeys = ['secret', 'privateKey'];
const signOptKeys = Object.keys(signOptions);
if (
typeof payload === 'string' &&
signOptKeys.some((k) => !allowedSignOptKeys.includes(k))
) {
throw new Error(
'Payload as string is not allowed with the following sign options: ' +
signOptKeys.join(', ')
);
}
return jwt.sign(payload, secret, signOptions);
}
signAsync(
payload: string,
options?: Omit<JwtSignOptions, keyof jwt.SignOptions>
): Promise<string>;
signAsync(
payload: Buffer | object,
options?: JwtSignOptions
): Promise<string>;
signAsync(
payload: string | Buffer | object,
options?: JwtSignOptions
): Promise<string> {
const signOptions = this.mergeJwtOptions(
{ ...options },
'signOptions'
) as jwt.SignOptions;
const secret = this.getSecretKey(
payload,
options,
'privateKey',
JwtSecretRequestType.SIGN
);
const allowedSignOptKeys = ['secret', 'privateKey'];
const signOptKeys = Object.keys(signOptions);
if (
typeof payload === 'string' &&
signOptKeys.some((k) => !allowedSignOptKeys.includes(k))
) {
throw new Error(
'Payload as string is not allowed with the following sign options: ' +
signOptKeys.join(', ')
);
}
return new Promise((resolve, reject) =>
jwt.sign(payload, secret, signOptions, (err, encoded) =>
err ? reject(err) : resolve(encoded)
)
);
}
verify<T extends object = any>(token: string, options?: JwtVerifyOptions): T {
const verifyOptions = this.mergeJwtOptions({ ...options }, 'verifyOptions');
const secret = this.getSecretKey(
token,
options,
'publicKey',
JwtSecretRequestType.VERIFY
);
return jwt.verify(token, secret, verifyOptions) as T;
}
verifyAsync<T extends object = any>(
token: string,
options?: JwtVerifyOptions
): Promise<T> {
const verifyOptions = this.mergeJwtOptions({ ...options }, 'verifyOptions');
const secret = this.getSecretKey(
token,
options,
'publicKey',
JwtSecretRequestType.VERIFY
);
return new Promise((resolve, reject) =>
jwt.verify(token, secret, verifyOptions, (err, decoded) =>
err ? reject(err) : resolve(decoded as T)
)
) as Promise<T>;
}
decode(
token: string,
options?: jwt.DecodeOptions
): null | { [key: string]: any } | string {
return jwt.decode(token, options);
}
private mergeJwtOptions(
options: JwtVerifyOptions | JwtSignOptions,
key: 'verifyOptions' | 'signOptions'
): jwt.VerifyOptions | jwt.SignOptions {
delete options.secret;
if (key === 'signOptions') {
delete (options as JwtSignOptions).privateKey;
} else {
delete (options as JwtVerifyOptions).publicKey;
}
return options
? {
...(this.options[key] || {}),
...options
}
: this.options[key];
}
private getSecretKey(
token: string | object | Buffer,
options: JwtVerifyOptions | JwtSignOptions,
key: 'publicKey' | 'privateKey',
secretRequestType: JwtSecretRequestType
): string | Buffer | jwt.Secret {
let secret = this.options.secretOrKeyProvider
? this.options.secretOrKeyProvider(secretRequestType, token, options)
: options?.secret ||
this.options.secret ||
(key === 'privateKey'
? (options as JwtSignOptions)?.privateKey || this.options.privateKey
: (options as JwtVerifyOptions)?.publicKey ||
this.options.publicKey) ||
this.options[key];
if (this.options.secretOrPrivateKey) {
this.logger.warn(
`"secretOrPrivateKey" has been deprecated, please use the new explicit "secret" or use "secretOrKeyProvider" or "privateKey"/"publicKey" exclusively.`
);
secret = this.options.secretOrPrivateKey;
}
return secret;
}
}