How does AuthGuard knows about the Passport Strategy?
In NestJS, the AuthGuard
knows about the Passport strategy through the PassportStrategy
class. This class is responsible for registering the Passport strategy with Passport and calling passport.authenticate()
within the AuthGuard()
.
Each strategy from a passport-*
package has a name
property, which is the name for the strategy. For example, for passport-local
, the name
is local
, and for passport-jwt
, the name is jwt
.
When you use AuthGuard()
in your controller, you can specify the strategy to use by passing the strategy name as an argument. For example:
This will tell the AuthGuard
to use the local
strategy.
If you don't specify a strategy name, the AuthGuard
will use the default strategy, which is set in the Passport module's options.
Here's a step-by-step explanation of how the AuthGuard
knows about the Passport strategy:
- You import the
AuthGuard
and the Passport strategy you want to use in your controller. - You use the
@UseGuards()
decorator to apply theAuthGuard
to your controller or a specific route. - The
AuthGuard
is instantiated, and thePassportStrategy
class is used to register the Passport strategy with Passport. - When a request is made to a protected route, the
AuthGuard
callspassport.authenticate()
with the appropriate strategy. - Passport authenticates the request using the specified strategy.
- If the authentication is successful, the request is allowed to continue. Otherwise, the request is rejected.
This is how the AuthGuard
knows about the Passport strategy and how it uses the strategy to authenticate requests.