In this article you'll be walked through the most straightforward guide of implementing authentication in NestJS, the most efficient scalable server-side applications builder among NodeJS frameworks.
We'll cover best practices, fundamental concepts that I believe you already have a slight prerequisite in by now and clearer examples. The purpose is to help you build the most robust authentication systems for your NestJS applications from simple concepts.
In simple words, Authentication is a process used to show that something or someone is legit, genuine or valid. hence authentication is a way of verifying if the user is really who they pretend to be before giving them access to a system or to some resources of this latter.
This goes hand in hand with Authorization, which is a process by which the server determines if a user has permission to have access on a specific resource of a system.
Developer Viewpoint Scenario
Before talking about Authentication, the client should register himself as a user of our system, and for that he will need to sign up, a process where he will post the credentials that will allow the system to recognize him later on.
Now talking of Authentication, the user will initiate the process by passing in his username/email and password, which will trigger the server to generate a JWT(Json Web Token) upon a successful authentication, Token that will then be transmitted as a bearer token in the authentication header for verification.
Step by Step guide:
Step_1. Create a resource for the users credentials
I assume that you already know how to create resources in NestJS, if not click here to learn how to do so.
Well, first thing first create a resource called maybe "user", this will manage the users credential data, remember the user credentials have to be stored somewhere, right ?
Step_2. Implement authentication in your REST API.
- Run the following command and when prompted donโt generate the CRUD, this auth is a special type of resource.
npm nest generate resource auth
- Install and configure passport(a library that manage authentication states).
npm install --save @nestjs/passport passport @nestjs/jwt passport-jwt
npm install --save-dev @types/passport-jwt
npm install passport-jwt
- In auth.modute.ts, add the following highlighted code-lines[by red dots ๐ด].
- Implement a POST endpoint at /auth/login
Create a new file called login.dto.ts inside the src/auth/dto folder and then define the LoginDto class interface based on the email and password properties for the login.
- Create a new file called auth.entity.ts inside the src/auth/entity that will describe the the shape of the jwt payload.
- Create a new login method inside the auth.service.ts file.
- Now, In auth.controller.ts create a POST endpoint at /auth/login
Step_3. Implement JWT authentication strategy
- First create a new file called jwt.strategy.ts inside the src/auth/strategy directory.
- Into Auth.module.ts import then add JwtStrategy in the imports and usersModule in the providers[see red dots ๐ด].
- To make UsersService accessible in our class(surely AuthService), you also need to add it in the exports of the UsersModule.
Step_4. Protecting our system resources from unverified users
- JWT auth guard will be used to protect routes that require authentication in order to be accessed, in our case let's protect the users resource API routes. so, in src/auth, create a file called jwt-auth.guard.ts.
NOTE: The AuthGuard class expects the name of an authentication strategy. In this case, you are using the JwtStrategy that you implemented in the previous section, which is named โjwtโ.
- You can now use this guard (UseGuards(JwtAuthGuard)) as a decorator to protect your endpoints. Add the JwtAuthGuard to routes in the UsersController.
NOTE: If you're using Swagger, integrate an authentication indication that will highlight the routes that are protected using the @ApiBearerAuth() decorator. first define it in main, then implement it in users.controller.ts.
AND NOW YOU'RE ALL SET๐ฎโ๐จ
Top comments (0)