• Stars
    star
    562
  • Rank 76,349 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 6 years ago
  • Updated 26 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JWT utilities module based on the jsonwebtoken package ๐Ÿ”“

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads Coverage Discord Backers on Open Collective Sponsors on Open Collective

Description

JWT utilities module for Nest based on the jsonwebtoken package.

Installation

$ npm i --save @nestjs/jwt

Usage

Import JwtModule:

@Module({
  imports: [JwtModule.register({ secret: 'hard!to-guess_secret' })],
  providers: [...],
})
export class AuthModule {}

Inject JwtService:

@Injectable()
export class AuthService {
  constructor(private readonly jwtService: JwtService) {}
}

Secret / Encryption Key options

If you want to control secret and key management dynamically you can use the secretOrKeyProvider function for that purpose.

JwtModule.register({
   /* Secret has precedence over keys */
  secret: 'hard!to-guess_secret',

  /* public key used in asymmetric algorithms (required if non other secrets present) */
  publicKey: '...',

  /* private key used in asymmetric algorithms (required if non other secrets present) */
  privateKey: '...',

  /* Dynamic key provider has precedence over static secret or pub/private keys */
  secretOrKeyProvider: (
    requestType: JwtSecretRequestType,
    tokenOrPayload: string | Object | Buffer,
    verifyOrSignOrOptions?: jwt.VerifyOptions | jwt.SignOptions
  ) => {
    switch (requestType) {
      case JwtSecretRequestType.SIGN:
        // retrieve signing key dynamically
        return 'privateKey';
      case JwtSecretRequestType.VERIFY:
        // retrieve public key for verification dynamically
        return 'publicKey';
      default:
        // retrieve secret dynamically
        return 'hard!to-guess_secret';
    }
  },
});

Async options

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.

1. Use factory

JwtModule.registerAsync({
  useFactory: () => ({
    secret: 'hard!to-guess_secret'
  })
});

Obviously, our factory behaves like every other one (might be async and is able to inject dependencies through inject).

JwtModule.registerAsync({
  imports: [ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    secret: configService.get<string>('SECRET'),
  }),
  inject: [ConfigService],
}),

2. Use class

JwtModule.registerAsync({
  useClass: JwtConfigService
});

Above construction will instantiate JwtConfigService inside JwtModule and will leverage it to create options object.

class JwtConfigService implements JwtOptionsFactory {
  createJwtOptions(): JwtModuleOptions {
    return {
      secret: 'hard!to-guess_secret'
    };
  }
}

3. Use existing

JwtModule.registerAsync({
  imports: [ConfigModule],
  useExisting: ConfigService,
}),

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.

API Spec

The JwtService uses jsonwebtoken underneath.

jwtService.sign(payload: string | Object | Buffer, options?: JwtSignOptions): string

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.

jwtService.signAsync(payload: string | Object | Buffer, options?: JwtSignOptions): Promise<string>

The asynchronous .sign() method.

jwtService.verify<T extends object = any>(token: string, options?: JwtVerifyOptions): T

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.

jwtService.verifyAsync<T extends object = any>(token: string, options?: JwtVerifyOptions): Promise<T>

The asynchronous .verify() method.

jwtService.decode(token: string, options: DecodeOptions): object | string

The decode method is an implementation of jsonwebtoken .decode().

The JwtModule takes an options object:

  • secret is either a string, buffer, or object containing the secret for HMAC algorithms
  • secretOrKeyProvider function with the following signature (requestType, tokenOrPayload, options?) => jwt.Secret (allows generating either secrets or keys dynamically)
  • signOptions read more
  • privateKey PEM encoded private key for RSA and ECDSA with passphrase an object { key, passphrase } read more
  • publicKey PEM encoded public key for RSA and ECDSA
  • verifyOptions read more
  • secretOrPrivateKey (DEPRECATED!) read more

Support

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.

Stay in touch

License

Nest is MIT licensed.

More Repositories

1

nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript ๐Ÿš€
TypeScript
64,389
star
2

awesome-nestjs

A curated list of awesome things related to NestJS ๐Ÿ˜Ž
9,674
star
3

nest-cli

CLI tool for Nest applications ๐Ÿน
TypeScript
1,868
star
4

typeorm

TypeORM module for Nest framework (node.js) ๐Ÿ‡
TypeScript
1,825
star
5

typescript-starter

Nest framework TypeScript starter โ˜•
TypeScript
1,753
star
6

swagger

OpenAPI (Swagger) module for Nest framework (node.js) ๐ŸŒŽ
TypeScript
1,590
star
7

graphql

GraphQL (TypeScript) module for Nest framework (node.js) ๐Ÿท
TypeScript
1,414
star
8

docs.nestjs.com

The official documentation https://docs.nestjs.com ๐Ÿ“•
TypeScript
1,101
star
9

cqrs

A lightweight CQRS module for Nest framework (node.js) ๐ŸŽˆ
TypeScript
791
star
10

terminus

Terminus module for Nest framework (node.js) ๐Ÿค–
TypeScript
633
star
11

throttler

A rate limiting module for NestJS to work with Fastify, Express, GQL, Websockets, and RPC ๐Ÿงญ
TypeScript
580
star
12

bull

Bull module for Nest framework (node.js) ๐Ÿฎ
TypeScript
567
star
13

passport

Passport module for Nest framework (node.js) ๐Ÿ”‘
TypeScript
477
star
14

mongoose

Mongoose module for Nest framework (node.js) ๐Ÿธ
TypeScript
476
star
15

config

Configuration module for Nest framework (node.js) ๐Ÿ“
TypeScript
467
star
16

ng-universal

Angular Universal module for Nest framework (node.js) ๐ŸŒท
TypeScript
440
star
17

serve-static

Serve static websites (SPA's) using Nest framework (node.js) ๐Ÿฅฆ
TypeScript
432
star
18

elasticsearch

Elasticsearch module based on the official elasticsearch package ๐ŸŒฟ
TypeScript
365
star
19

schematics

Nest architecture element generation based on Angular schematics ๐ŸŽฌ
TypeScript
355
star
20

mapped-types

Configuration module for Nest framework (node.js) ๐Ÿบ
TypeScript
349
star
21

schedule

Schedule module for Nest framework (node.js) โฐ
TypeScript
325
star
22

sequelize

Sequelize module for Nest framework (node.js) ๐Ÿˆ
TypeScript
210
star
23

axios

Axios module for Nest framework (node.js) ๐Ÿ—‚
TypeScript
202
star
24

serverless-core-deprecated

[Deprecated] Serverless Core module for Nest framework (node.js) ๐ŸฆŠ
TypeScript
168
star
25

event-emitter

Event Emitter module for Nest framework (node.js) ๐Ÿฆ‹
TypeScript
167
star
26

azure-func-http

Azure Functions HTTP adapter for Nest framework (node.js) ๐ŸŒฅ
TypeScript
146
star
27

nestjs.com

The official website https://nestjs.com ๐Ÿ†
HTML
127
star
28

javascript-starter

Nest framework JavaScript (ES6, ES7, ES8) + Babel starter ๐Ÿฐ
JavaScript
111
star
29

courses.nestjs.com

Official NestJS Courses website https://courses.nestjs.com ๐Ÿก
HTML
104
star
30

azure-database

Azure CosmosDB Database module for Nest framework (node.js) โ˜๏ธ
TypeScript
101
star
31

cache-manager

Cache manager module for Nest framework (node.js) ๐Ÿ—ƒ
TypeScript
99
star
32

azure-storage

Azure Storage module for Nest framework (node.js) โ˜๏ธ
TypeScript
83
star
33

azure-serverless-deprecated

[Deprecated] Azure Serverless module for Nest framework (node.js) ๐ŸŒฉ
TypeScript
44
star
34

enterprise.nestjs.com

The official website https://enterprise.nestjs.com ๐ŸŒ
HTML
15
star
35

newsletter.nestjs.com

Official NestJS Newsletter website https://newsletter.nestjs.com ๐Ÿ“ฉ
HTML
3
star