Notification texts go here Contact Us Buy Now!

NestJS - How does AuthGuard knows about the Passport Strategy?

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:

```html @UseGuards(AuthGuard('local')) ```

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:

  1. You import the AuthGuard and the Passport strategy you want to use in your controller.
  2. You use the @UseGuards() decorator to apply the AuthGuard to your controller or a specific route.
  3. The AuthGuard is instantiated, and the PassportStrategy class is used to register the Passport strategy with Passport.
  4. When a request is made to a protected route, the AuthGuard calls passport.authenticate() with the appropriate strategy.
  5. Passport authenticates the request using the specified strategy.
  6. 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.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.