Adding Route Protections with Guards
Explore how to implement route protection in NestJS by creating and applying guards that validate JWT tokens. You'll learn to restrict access to endpoints, handle token verification, and manage unauthorized requests effectively.
We'll cover the following...
In our virtual library, the /books endpoint is reserved for authenticated users only. In this lesson, we will use a NestJS guard to enforce this restriction by validating JWT tokens attached to incoming requests.
Generating AuthGuard
To generate AuthGuard, run the nest g guard auth --no-spec command in the terminal below:
This command will create an auth.guard.ts file in the auth folder with the following boilerplate code:
The AuthGuard class implements the CanActivate interface, necessitating a canActivate() method. The canActivate() method receives an ExecutionContext object as a parameter, which holds details about the current request cycle.
The return value expected by the canActivate method is a boolean. It can return this value (boolean) synchronously or asynchronously: Promise<boolean> or (Observable<boolean>).
In the current implementation, the canActivate() method allows all requests by ...