In this article, we are going to explore the implementation steps of JWT(JSON Web Token) authentication in the NestJS application. In this process of authentication, we going to use the 'passport' library(nodejs library) where we write simple customizable authentication.
Create A Sample NestJS Application:
Let's understand step by step implementation authentication in NestJs application, so let's begin our journey by creating a sample application.
Command To Install CLI:
npm i -g @nestjs/cli
Command To Create NestJS App:
nest new your_project_name
Create Users Model:
Create a 'User' model that represents the table. For now, let's create a simple class in the upcoming steps we make it compatible to communicate with the database.
src/users/users.ts:
export class User{ id:number; userName: string; password: string; }
Create A UsersService:
The 'UsersService' is a logical container for our 'Users' data. For now, just mock the user's data, later we make dynamic by using the database.
src/users/users.service.ts:
import { Injectable } from '@nestjs/common'; import { User } from './users'; @Injectable() export class UsersService { private readonly users: User[]; constructor() { this.users = [ { id: 1, userName: 'naveen', password: '1234', }, { id: 2, userName: 'ramanajee', password: '2345', }, { id: 3, userName: 'gopi', password: '3456', }, { id: 4, userName: 'rama krishna', password: '4567', }, ]; } async findOne(username: string): Promise<User | undefined> { return this.users.find(user => user.userName === username); } }
- (Line: 4) The 'Injectable' decorator makes our 'UsersService' injectable service. The 'Injectable' decorator loads from '@nestjs/common'.
- (Line: 9) Initialized collection of mocked user data.
- (Line: 33) The 'findOne' method to filters by the 'userName.'
Create A UsersModule:
src/users/users.module.ts:
import { Module } from '@nestjs/common'; import { UsersService } from './users.service'; @Module({ providers: [UsersService], exports:[UsersService] }) export class UsersModule {}
- (Line: 6) The 'UsersService' exports to make it available to other modules to use it.
Create A AuthService:
The 'AuthService' to validate the users by using the 'UsersService'. Currently, the 'AuthService' may look not more useful, but when we implement JWT authentication it will be more useful.
src/auth/auth.service.ts:
import { Injectable } from '@nestjs/common'; import { UsersService } from '../users/users.service'; @Injectable() export class AuthService { constructor(private usersService:UsersService){ } async validateUser(userName:string, pass:string):Promise<any>{ const user = await this.usersService.findOne(userName); if(user && user.password === pass){ const result = { id: user.id, userName: user.userName }; return result; } return null; } }
- (Line: 7) Injected 'UsersService' into the 'AuthService'.
- The 'validateUser' method check for the user and if the user exists returns some information about the user(never return password in the user information).
Create AuthModule:
src/auth/aut.module.ts:
import { Module } from '@nestjs/common'; import { AuthService } from './auth.service'; import { UsersModule } from '../users/users.module'; @Module({ imports: [UsersModule], providers: [AuthService], }) export class AuthModule {}
- (Line: 6) Since we are using 'UsersService' which is in 'UsersModule', so 'UsersModule' imported into the 'AuthModule'.
Create A Login Endpoint:
Import 'AuthModule', 'UsersModule' into the AppModule file.
src/app.module.ts:
import { Module } from '@nestjs/common'; import { AuthModule } from './auth/auth.module'; import { UsersModule } from './users/users.module'; // code hidden for display purpose @Module({ imports: [AuthModule, UsersModule] }) export class AppModule {}Let's add the 'Login' endpoint with the fake credentials as below.
src/app.controller.ts:
import { Controller, Post } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import {AuthService} from './auth/auth.service'; @Controller() export class AppController { constructor(private authService:AuthService) {} @Post('auth/login') async login(){ return await this.authService.validateUser("naveen","1234"); } }
- (Line: 8) Injected 'Authservice'
- The 'Login' endpoint created by validating dummy users and returns user info.
src/auth/aut.module.ts:
import { Module } from '@nestjs/common'; import { AuthService } from './auth.service'; // existing code hiden for display purpose @Module({ exports:[AuthService] }) export class AuthModule {}Now let's test the endpoint which returns the user info like below:
Passport Library:
- Passport is the most popular node.js authentication library.
- The 'Passport' library integration involves 'Strategy'. The 'Strategy' is used for reading the user credentials and validating them by invoking the 'validation()' method to check for the valid user.
- After successfully validating the user, then the 'Passport' attaches the user information to the 'Request' object which will be used by the route handlers.
passport-local Library:
By extending the 'Passport' library there are so many different strategies that are available as separate plugins. The 'passport-local' library is one such strategy.
The 'passport-local' strategy to authenticate the user using 'username' and 'password'. These values will be read by the strategy from the body of the request. By default 'username' and 'password' parameter names should be the same as here we mentioned, if we pass the values with different names then the PassportStrategy unable to read the values. So to make use of custom payload variable name we need to specify those names at the time of local PassportStrategy configuration using the options 'usernameField', 'passwordField'.
Install passport-local Npm Packages:
Command To Install passport-local Packages:
npm install --save @nestjs/passport passport passport-local
npm install --save-dev @types/passport-local
- The package '@nestjs/passport' is a wrapper that makes the 'passport' library easily understand by NestJS
- The 'passport' is a nodejs authentication library.
- The 'passport-local' package is one of the strategies of 'passport'.
- The '@types/passport-local' package for typescript.
Authenticate User Using Passport Local Strategy:
The 'passport-local' strategy is an authentication strategy that validates the user by the 'username' and 'password'. Adds the user info to the request object on authentication.
src/auth/local.strategy.ts:
import { PassportStrategy } from '@nestjs/passport'; import { Strategy } from 'passport-local'; import { Injectable, UnauthorizedException } from '@nestjs/common'; import { AuthService } from './auth.service'; @Injectable() export class LocalStrategy extends PassportStrategy(Strategy) { constructor(private authService: AuthService) { super(); } async validate(username: string, password: string):Promise<any> { const user = this.authService.validateUser(username, password); if(!user){ throw new UnauthorizedException(); } return user } }
- (Line: 8) The 'LocalStrategy' extends the 'PassportStrategy'. The 'PassportStratety' loads from the '@nestjs/passport' library. The 'PassportStrategy' is a generic type interface for extending it we need to specify the type of strategy we are going to extend. Here we define the type as 'Strategy' which loads from 'passport-local', that proves that were implementing the passport-local strategy.
- (Line: 10) The 'super()' invokes the 'PassportStartegy' from the constructor. To this, we pass the javascript object literal as optional input params. The input params contain where we can override the variable names of 'username' and 'password'. For this sample, we are going to use default variables.
- The 'validate(username: string, password: string)' method gets executed automatically on invoking of our 'LocalStartegy'. This method will validate the 'Users' and returns 'user' if valid. This user info will be added to the 'Request' object which can be used by the route handler. Since we haven't overridden the variables of 'username' and 'password', then our 'validate' method signature should look like we defined here.
src/auth/auth.module.ts:
import { Module } from '@nestjs/common'; import { AuthService } from './auth.service'; import { UsersModule } from '../users/users.module'; import { PassportModule } from '@nestjs/passport'; import { LocalStrategy } from './local.strategy'; @Module({ imports: [UsersModule, PassportModule], providers: [AuthService, LocalStrategy], exports:[AuthService] }) export class AuthModule {}
- (Line: 8) Imported 'PassportModule'
- (Line: 9) Added 'LocalStrategy' to providers.
UseGuards To Invoke passport-local Strategy:
Now login endpoint using 'UseGuards' attribute we will invoke the 'passport-local' strategy.
src/app.controller.ts:
import { Controller, Get, Request, UseGuards, Post } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Controller() export class AppController { @UseGuards(AuthGuard('local')) @Post('auth/login') async login(@Request() req){ return req.user; } }
- (Line: 6) The endpoint decorated with '@UseGuard()' attribute, the '@UseGuard()' load from '@nestjs/common'. The '@UseGuard()' takes 'AuthGuard()' from '@nestjs/passport'. The 'local' default name to invoke 'passport-local' strategy, if we want we can override the name(overriding of strategy name will be discussed in 'passport-jwt' strategy in the later steps). Without name also strategy gets invoked automatically if we have only one strategy in our application, but if we have multiple then we need to specify the name explicitly like we did here(used 'local' name in AuthGuard).
- (Line: 8) Here we can observe instead of user payload('username', 'password' etc) we used '@Request' object loads from '@nestjs/common'. The reason behind this our 'AuthGuard' invokes our 'LocalStrategy' which will validate the user and add the user info to the 'Request' object.
Now if we access the endpoint, we will get the user info validated by the 'passport-local' strategy.
JSON Web Token:
Till now in our sample application, we only validated the user. Now we need to generate the Access Token to authenticate a user so that the Access token will be used in subsequent API calls to make the user authenticated.
One of the most popular techniques to generate Access Token is JWT(JSON Web Token). The JWT, in general, is an encrypted string that contains the user info to validate against the backend. The integration and implementation of JWT involve very simple steps we discuss in upcoming steps.
Install NestJS JWT Npm Package:
Command To Install NestJS Jwt Package:
npm install --save @nestjs/jwt
Configure JwtModule:
Now in 'AuthModule' register the JwtModule with some basic configuration options.
src/aut/aut.module.ts:
import { Module } from '@nestjs/common'; import { AuthService } from './auth.service'; import { UsersModule } from '../users/users.module'; import { PassportModule } from '@nestjs/passport'; import { LocalStrategy } from './local.strategy'; import {JwtModule} from '@nestjs/jwt'; @Module({ imports: [UsersModule, PassportModule, JwtModule.register({ secret: "My Secret Never let outsiders", signOptions:{ expiresIn: '60s' } })], providers: [AuthService, LocalStrategy], exports:[AuthService] }) export class AuthModule {}
- (Line: 12) The 'secret' value is used to encryption the Jwt token. In production application don't hard code in code itself, make it accessible from the secured configuration file.
- (Line: 13) The 'expiresIn' defines the time for end of the token. It takes string value like '50s', '2days', '10h', '7d', etc.
Use JwtService Sign Method:
The '@nestj/jwt' provides us 'JwtService' provider contains a method called 'sign()' method to generate the token. Now let's add a new method in 'AuthService' as follows.
src/auth/aut.service.ts:
import { Injectable } from '@nestjs/common'; import { UsersService } from '../users/users.service'; import {JwtService} from '@nestjs/jwt' // existing code hidden for display @Injectable() export class AuthService { constructor(private usersService:UsersService, private jwtService:JwtService){ } async login(user:any){ const payload = {username: user.userName, sub: user.userId}; return{ accessToken : this.jwtService.sign(payload) } } }
- (Line: 8) Injected 'JwtService' loaded from the '@nestjs/jwt'
- The login method takes user info as input data, then create a payload to store in the 'Jwt' token. Uses the 'sign()' method of 'JwtService' to generate the token. Along with payload the configurations we made in the JwtModule will be used on creating the token.
Login Endpoint Returns Token:
Now update the login endpoint to returns the jwt token.
src/app.controller.cs:
import { Controller, Get, Request, UseGuards, Post } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import {AuthService} from './auth/auth.service'; @Controller() export class AppController { constructor( private readonly authService:AuthService) {} @UseGuards(AuthGuard('local')) @Post('auth/login') async login(@Request() req){ return this.authService.login({userId: req.user.id, userName: req.user.username}); } }
- After validating the user against our 'passport-local' strategy, the valid use info appended to the request object is passed as input data to the 'login()' method in AuthService.
passport-jwt Library:
The 'passport-jwt' is another type of strategy where secure rest API by validating the authentication token. This strategy will validate the auth token and decrypt the user information and add it to the 'Request' object which will be used route handler.
Install passport-jwt Npm Package:
Command To Install Passport Jwt:
npm install --save passport-jwt
npm install --save-dev @types/passport-jwt
Create A Todos Endpoint:
Now let's create a Todos endpoint which we will protect it using the JWT token in upcoming steps.
src/app.controller.ts:
@Get('todos') getTodos(){ return ['Watch Movie', 'Take Health Test', 'Play Cricket']; }
Create A JwtStrategy To Validate AccessToken:
Using 'passport-jwt' we are going to create a 'JwtStrategy' provider which will validate the access token.
src/auth/jwt.strategy.ts:
import { PassportStrategy } from '@nestjs/passport'; import { Strategy, ExtractJwt } from 'passport-jwt'; import {Injectable} from '@nestjs/common'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: 'My Secret Never let outsiders', }); } async validate(payload: any) { return { userId: payload.sub, username: payload.username }; } }
- (Line: 6) The 'JwtStrategy' extends 'PassportStrategy'. The 'PassportStrategy' is loads from '@nestjs/passport'. The 'Strategy' is the type of the 'PassportStrategy' which loads from 'passport-jwt'. From this, we can confirm 'JwtStrategy' is the 'passport-jwt' strategy.
- (Line: 8-12) Configuration for our 'JwtStrategy'. The property 'jwtFromRequest' it accepts the access token from our request. The 'ExtracJwt' instance is to fetch access token from like headers, query parameters, body, etc. In this sample in 'JwtStrategy', we fetch token from authorization request header using 'ExtractJwt.froAuthHeaderAsBearrToken()'. The 'ignoreExpiration' property accepts a boolean value, if the value is true then 'JwtStrategy' ignores to check token expiration on validation, if the value is false then 'JwtStrategy' will check for the expiration date. The 'secretOrkey' property value must match the key used in the JwtMdoule.
- The 'Validate()' method gets executed for valid token and returns the user info by adding it to the 'Request' object.
Use 'jwt' AuthGuard On Todo Endpoint:
Now let's protect our 'Todo' endpoint using the 'jwt' AuthGuard.
src/app.controller.cs:
@UseGuards(AuthGuard('jwt')) @Get('todos') getTodos(){ return ['Watch Movie', 'Take Health Test', 'Play Cricket']; }The 'AuthGaurd('jwt')' invokes the JwtStrategy for the access token validation. The 'jwt' is the default name to invoke the 'passport-jwt' strategy.
Let's test the endpoint first without an access token.
Now add authorization header with access token as value and test the Todo endpoint.Finally, we have implemented an access token and used against a secure endpoint to access the data.Database Integration:
Till now we have used mocked data for user authentication. Now we will integrate the database. Here we will use the PostgreSQL relational database. Click here for a detailed implementation of the PostgreSQL relational database integration in the NestJS application.
Install Packages:
npm install --save @nestjs/typeorm
npm install --save typeorm
npm install --save pg
Note:
In the entire sample i have used plain password for demo purpose. While developing real time application please do encrypt, hash your password before saving to database using plugin like 'bcrypt' plugin.
Update the 'User' model by making it compatible with database communication as below.src/users/users.ts:
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; @Entity() export class User{ @PrimaryGeneratedColumn() id:number; @Column({name:"username"}) userName: string; @Column() password: string; }Now update the 'UserService' to fetch the user data from the database.
src/users/users.service.ts:
import { Injectable } from '@nestjs/common'; import { User } from './users'; import { Repository } from 'typeorm'; import { InjectRepository } from '@nestjs/typeorm'; @Injectable() export class UsersService { constructor(@InjectRepository(User) private userRepo: Repository<User>){ } async findOne(userName: string): Promise<User | undefined> { return this.userRepo.findOne({userName}); } }Now import the typeorm feature module in the UserModule to inject the repository in the services.
src/users/users.module.ts:
import { Module } from '@nestjs/common'; import { UsersService } from './users.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import {User} from './users'; @Module({ imports:[TypeOrmModule.forFeature([User])], providers: [UsersService], exports:[UsersService] }) export class UsersModule {}Now add the database configuration settings in the AppModule.
src/app.module.ts:
import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { AuthModule } from './auth/auth.module'; import { UsersModule } from './users/users.module'; import { TypeOrmModule } from '@nestjs/typeorm'; import {User} from './users/users'; @Module({ imports: [ TypeOrmModule.forRoot({ type: 'postgres', host: 'lallah.db.elephantsql.com', port: 5432, username: 'wloatmii', password: '********', database: 'wloatmii', entities: [User], }), AuthModule, UsersModule], controllers: [AppController], providers: [AppService], }) export class AppModule {}That's all we have successfully integrated the PostgreSQL database with our sample application. In the next part, we are going to implement the refresh token.
Support Me!
Buy Me A Coffee
PayPal Me
Wrapping Up:
Hopefully, I think this article delivered some useful information on the Jwt authentication in the NestJS application. I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment