Introduction
User authentication is a critical aspect of any application, providing a layer of security to protect user data and sensitive information.
Passport is the most popular node.js authentication library that is successfully used in many production applications. Nest applications can be integrated with the Passport library using the @nestjs/passport module.
Passport uses the concept of strategies to authenticate requests. Strategies can range from verifying username and password credentials, delegated authentication using OAuth (for example, via Facebook or Twitter) etc.
In this article, we are making use of two passport strategies, namely:
- passport-local: to authenticate a user based on username and password
- passport-jwt: to authenticate a user based on the JSON Web Token.
After an initial successful local username and password authentication by the user, corresponding JWT can be generated. This JWT can then be used to get authenticated when accessing subsequent protected routes within the application.
Pre-requisites
In a real world Nest application, following setup would have been completed before implementing user authentication:
- Install Nest CLI and create a new project.
- Install
@nestjs/configto read environment variables. - Install client API libraries for TypeORM and PostgreSQL.
- Configure the database module using
ConfigService.
Local authentication
Local authentication refers to when the client application or end-user sends in username and password for login, to a login API route. A guard named ‘LocalAuthGuard’ is placed in front of the login route to handle these requests.
The @nestjs/passport module provides a built-in guard ‘AuthGuard’ that invokes the required Passport strategy. In this case, it invokes the passport-local strategy.
JWT authentication
JWT authentication involves sending a valid JWT as a bearer token in the authorization header of subsequent requests. The ‘JwtAuthGuard’ invokes the passport-jwt strategy to extract and verify the token.
Conclusion
Mastering user authentication in NestJS using Passport and JWT is crucial for building secure applications. It ensures that users can securely log in and that protected resources are only accessible to authenticated users.



