1 | <p align="center">
|
2 | <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
3 | </p>
|
4 |
|
5 | [travis-image]: https://api.travis-ci.org/nestjs/nest.svg?branch=master
|
6 | [travis-url]: https://travis-ci.org/nestjs/nest
|
7 | [linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux
|
8 | [linux-url]: https://travis-ci.org/nestjs/nest
|
9 |
|
10 | <p align="center">A progressive <a href="http://nodejs.org" target="blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
11 | <p align="center">
|
12 | <a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
13 | <a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
14 | <a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
|
15 | <a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#5" alt="Coverage" /></a>
|
16 | <a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
17 | <a href="https://opencollective.com/nest#backer"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
18 | <a href="https://opencollective.com/nest#sponsor"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
19 | <a href="https://paypal.me/kamilmysliwiec"><img src="https://img.shields.io/badge/Donate-PayPal-dc3d53.svg"/></a>
|
20 | <a href="https://twitter.com/nestframework"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
|
21 | </p>
|
22 | |
23 | [![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
|
24 |
|
25 | ## Description
|
26 |
|
27 | JWT utilities module for [Nest](https://github.com/nestjs/nest) based on the [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken) package.
|
28 |
|
29 | ## Installation
|
30 |
|
31 | ```bash
|
32 | $ npm i --save @nestjs/jwt
|
33 | ```
|
34 |
|
35 | ## Usage
|
36 |
|
37 | Import `JwtModule`:
|
38 |
|
39 | ```typescript
|
40 | @Module({
|
41 | imports: [JwtModule.register({ secret: 'hard!to-guess_secret' })],
|
42 | providers: [...],
|
43 | })
|
44 | export class AuthModule {}
|
45 | ```
|
46 |
|
47 | Inject `JwtService`:
|
48 |
|
49 | ```typescript
|
50 | @Injectable()
|
51 | export class AuthService {
|
52 | constructor(private readonly jwtService: JwtService) {}
|
53 | }
|
54 | ```
|
55 |
|
56 | ## Secret / Encryption Key options
|
57 |
|
58 | If you want to control secret and key management dynamically you can use the `secretOrKeyProvider` function for that purpose. You also can use asynchronous version of `secretOrKeyProvider`.
|
59 | NOTE: For asynchronous version of `secretOrKeyProvider`, synchronous versions of `.sign()` and `.verify()` will throw an exception.
|
60 |
|
61 | ```typescript
|
62 | JwtModule.register({
|
63 | /* Secret has precedence over keys */
|
64 | secret: 'hard!to-guess_secret',
|
65 |
|
66 | /* public key used in asymmetric algorithms (required if non other secrets present) */
|
67 | publicKey: '...',
|
68 |
|
69 | /* private key used in asymmetric algorithms (required if non other secrets present) */
|
70 | privateKey: '...',
|
71 |
|
72 | /* Dynamic key provider has precedence over static secret or pub/private keys */
|
73 | secretOrKeyProvider: (
|
74 | requestType: JwtSecretRequestType,
|
75 | tokenOrPayload: string | Object | Buffer,
|
76 | verifyOrSignOrOptions?: jwt.VerifyOptions | jwt.SignOptions
|
77 | ) => {
|
78 | switch (requestType) {
|
79 | case JwtSecretRequestType.SIGN:
|
80 | // retrieve signing key dynamically
|
81 | return 'privateKey';
|
82 | case JwtSecretRequestType.VERIFY:
|
83 | // retrieve public key for verification dynamically
|
84 | return 'publicKey';
|
85 | default:
|
86 | // retrieve secret dynamically
|
87 | return 'hard!to-guess_secret';
|
88 | }
|
89 | },
|
90 | });
|
91 | ```
|
92 |
|
93 | ## Async options
|
94 |
|
95 | Quite often you might want to asynchronously pass your module options instead of passing them beforehand. In such case, use `registerAsync()` method, that provides a couple of various ways to deal with async data.
|
96 |
|
97 | **1. Use factory**
|
98 |
|
99 | ```typescript
|
100 | JwtModule.registerAsync({
|
101 | useFactory: () => ({
|
102 | secret: 'hard!to-guess_secret'
|
103 | })
|
104 | });
|
105 | ```
|
106 |
|
107 | Obviously, our factory behaves like every other one (might be `async` and is able to inject dependencies through `inject`).
|
108 |
|
109 | ```typescript
|
110 | JwtModule.registerAsync({
|
111 | imports: [ConfigModule],
|
112 | useFactory: async (configService: ConfigService) => ({
|
113 | secret: configService.get<string>('SECRET'),
|
114 | }),
|
115 | inject: [ConfigService],
|
116 | }),
|
117 | ```
|
118 |
|
119 | **2. Use class**
|
120 |
|
121 | ```typescript
|
122 | JwtModule.registerAsync({
|
123 | useClass: JwtConfigService
|
124 | });
|
125 | ```
|
126 |
|
127 | Above construction will instantiate `JwtConfigService` inside `JwtModule` and will leverage it to create options object.
|
128 |
|
129 | ```typescript
|
130 | class JwtConfigService implements JwtOptionsFactory {
|
131 | createJwtOptions(): JwtModuleOptions {
|
132 | return {
|
133 | secret: 'hard!to-guess_secret'
|
134 | };
|
135 | }
|
136 | }
|
137 | ```
|
138 |
|
139 | **3. Use existing**
|
140 |
|
141 | ```typescript
|
142 | JwtModule.registerAsync({
|
143 | imports: [ConfigModule],
|
144 | useExisting: ConfigService,
|
145 | }),
|
146 | ```
|
147 |
|
148 | It works the same as `useClass` with one critical difference - `JwtModule` will lookup imported modules to reuse already created `ConfigService`, instead of instantiating it on its own.
|
149 |
|
150 | ## API Spec
|
151 |
|
152 | The `JwtService` uses [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken) underneath.
|
153 |
|
154 | #### jwtService.sign(payload: string | Object | Buffer, options?: JwtSignOptions): string
|
155 |
|
156 | The sign method is an implementation of jsonwebtoken `.sign()`. Differing from jsonwebtoken it also allows an additional `secret`, `privateKey`, and `publicKey` properties on `options` to override options passed in from the module. It only overrides the `secret`, `publicKey` or `privateKey` though not a `secretOrKeyProvider`.
|
157 | NOTE: Will throw an exception for asynchronous version of `secretOrKeyProvider`;
|
158 |
|
159 | #### jwtService.signAsync(payload: string | Object | Buffer, options?: JwtSignOptions): Promise\<string\>
|
160 |
|
161 | The asynchronous `.sign()` method.
|
162 |
|
163 | #### jwtService.verify\<T extends object = any>(token: string, options?: JwtVerifyOptions): T
|
164 |
|
165 | The verify method is an implementation of jsonwebtoken `.verify()`. Differing from jsonwebtoken it also allows an additional `secret`, `privateKey`, and `publicKey` properties on `options` to override options passed in from the module. It only overrides the `secret`, `publicKey` or `privateKey` though not a `secretOrKeyProvider`.
|
166 | NOTE: Will throw an exception for asynchronous version of `secretOrKeyProvider`;
|
167 |
|
168 | #### jwtService.verifyAsync\<T extends object = any>(token: string, options?: JwtVerifyOptions): Promise\<T\>
|
169 |
|
170 | The asynchronous `.verify()` method.
|
171 |
|
172 | #### jwtService.decode(token: string, options: DecodeOptions): object | string
|
173 |
|
174 | The decode method is an implementation of jsonwebtoken `.decode()`.
|
175 |
|
176 | The `JwtModule` takes an `options` object:
|
177 |
|
178 | - `secret` is either a string, buffer, or object containing the secret for HMAC algorithms
|
179 | - `secretOrKeyProvider` function with the following signature `(requestType, tokenOrPayload, options?) => jwt.Secret | Promise<jwt.Secret>` (allows generating either secrets or keys dynamically)
|
180 | - `signOptions` [read more](https://github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback)
|
181 | - `privateKey` PEM encoded private key for RSA and ECDSA with passphrase an object `{ key, passphrase }` [read more](https://github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback)
|
182 | - `publicKey` PEM encoded public key for RSA and ECDSA
|
183 | - `verifyOptions` [read more](https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback)
|
184 | - `secretOrPrivateKey` (DEPRECATED!) [read more](https://github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback)
|
185 |
|
186 | ## Support
|
187 |
|
188 | Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
189 |
|
190 | ## Stay in touch
|
191 |
|
192 | - Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
193 | - Website - [https://nestjs.com](https://nestjs.com/)
|
194 | - Twitter - [@nestframework](https://twitter.com/nestframework)
|
195 |
|
196 | ## License
|
197 |
|
198 | Nest is [MIT licensed](LICENSE).
|