Skip to content

About

An authentication module for NestJS (Node.js) ๐Ÿ”

Topics

Resources

Contributing

Security policy

Stars

16 stars

Watchers

1 watching

Forks

Latest commit

ย 

History

131 Commits

Folders and files

Repository files navigation

Nest Logo

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

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

Description

Authentication module for Nest: a global guard with @Public() and @Authenticate(), credential providers as ordinary injectable classes (bearer JWT, cookie sessions, your own), server-side sessions with rotation, refresh tokens, TOTP second factor, magic links, OIDC sign-in, email verification and password reset, across HTTP, GraphQL, WebSockets, microservices and MCP tool calls (@nestjs/mcp), with no third-party dependencies.

Installation

$ npm i --save @nestjs/authentication

Quick Start

Import the module. Its global guard then requires a signed-in user on every route:

@Module({
  imports: [
    AuthenticationModule.forRoot({
      accessToken: {
        key: process.env.JWT_SECRET!,
        issuer: 'https://api.example.com',
        audience: 'web',
        ttl: '15m',
      },
    }),
  ],
  providers: [JwtAuth],
})
export class AppModule {}

key is a secret of at least 32 bytes for HS256 (openssl rand -base64 32), or a private key. To keep a shorter secret that other services already sign or verify with, add allowShortSecret: true: tokens stay plain HS256 with that secret, and startup logs a warning, since anyone holding a token can guess a short secret offline.

Credential providers are ordinary injectable classes that register themselves with AuthenticationRegistry:

@Injectable()
export class JwtAuth extends JwtBearerProvider<User> {
  constructor(
    private readonly users: UsersRepository,
    registry: AuthenticationRegistry,
  ) {
    super(); // verifies the tokens the module's `accessToken` option signs
    registry.registerProvider(this);
  }

  validate({ sub }: JwtClaims) {
    return sub ? this.users.findById(sub) : null;
  }
}

Then use @Public() to opt a route out, and @Authenticate() to change what a route requires:

@Controller()
export class AppController {
  @Public()
  @Get('health')
  health() {
    return 'ok';
  }

  @Get('me')
  me(@CurrentUser() user: User) {
    return user;
  }

  // Anonymous callers get through too: `user` is then `null`.
  @Authenticate({ optional: true })
  @Get('greeting')
  greeting(@CurrentUser() user: User | null) {
    return user ? `Hello, ${user.email}` : 'Hello, guest';
  }
}

Passwords

PasswordHasher (injectable, no setup) hashes with scrypt from node:crypto. Pass the stored hash to verify() even when there is no user: it then checks a dummy hash, so an unknown email takes as long as a wrong password and the response time doesn't reveal which emails are registered.

@Injectable()
export class CredentialsService {
  constructor(
    private readonly users: UsersRepository,
    private readonly passwordHasher: PasswordHasher,
  ) {}

  async register(email: string, password: string) {
    return this.users.create(email, { passwordHash: await this.passwordHasher.hash(password) });
  }

  /** The user, or `null` for a wrong email or password. */
  async verify(email: string, password: string) {
    const found = await this.users.findCredentials(email);
    const valid = await this.passwordHasher.verify(password, found?.passwordHash);
    return valid && found ? found.user : null;
  }
}

The in-memory stores are fine in development. In production, startup fails until you register real stores with AuthenticationStorage.registerSource() for everything your features use (a SessionCookieProvider uses the sessions store, accessToken the refreshTokens store unless refreshToken: false, and mfa, off unless configured, the mfa store), or you set allowInMemoryStorage: true. Read Overview & Tutorial for sessions, refresh tokens, TOTP, magic links, OIDC and account flows.

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.

About

An authentication module for NestJS (Node.js) ๐Ÿ”

Topics

Resources

Contributing

Security policy

Stars

16 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages