Member-only story
JWT and Passport JWT Strategy for Your NestJS REST API Project
A step-by-step and detailed implementation
Building blocks — Short Intro
When it comes to apps authentication (e.g., users’ authentication), the JSON Web Tokens (JWT) based Authentication is one of the most widely spread options, amongst other choices such as browser Cookies and Session Authentication, OAuth/OAuth2, and OpenID Connect.
Anyone can adopt and implement JWT in any project. For instance, NestJS offers us the solo @nestjs/jwt
module that allows us to integrate JWT in our project. However, it requires a lot of boilerplate. Thus, using an external tool/package, specialized in authentication, might be the preferred solution.
The Passport package is a massively used NodeJS library, whose “sole purpose is to authenticate requests, which it does through an extensible set of plugins known as strategies. Till the time this post was been writing, the Passport arsenal was consisted of about 537 strategies! Especially, for the JWT based Authentication, the Passport, of course, offers us the respective JWT strategy.
Since the Passport is the most popular NodeJS authentication library, NestJS offers its own @nestjs/passport
module which allows straightforward integration of the Passport to any NestJS application.
And this post aims to give you a hand on how to implement it. Actually, we are going to see how we can easily protect some of our routes (endpoints) using JWT and Passport’s JWT strategy. Safeguarding routes (endpoints and even entire Controller routes) is pretty straightforward using the AuthGuard() function provided by the Passport package.
NestJS documentation provides a quite similar example, and it is presumed that you have already taken some of the steps described there. However, here we will go through 2 steps.
- First, we will use JSON Web Tokens for users’ authentication
- then will continue to protect our routes (basic endpoints) using the Passport package and apply the JWT Strategy.
A base Repository
For your convenience (with respect to your time), you can use an example GitHub repo of mine…