A progressive Node.js framework for building efficient and scalable server-side applications.
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 and microservices, with no third-party dependencies.
$ npm i --save @nestjs/authenticationImport 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 {}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';
}
}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.
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.
- Author - Kamil Myśliwiec
- Website - https://nestjs.com
- Twitter - @nestframework
Nest is MIT licensed.