if i can use: "export class LocalStrategy extends PassportStrategy(Strategy,'local') {}"
why is necessary or why do i need to create:
"export class LocalAuthGuard extends AuthGuard('local') {}"
i was using in Controller guards like both of them i mentioned above but when i use in controller :
"@UseGuards(AuthGuard('local'))"
it calls only PassportStrategy class
and when i use in controller like this: @UseGuards(LocalAuthGuard) it is executed both of them like:
"class LocalStrategy extends PassportStrategy(Strategy,'local') {"
and
"class LocalAuthGuard extends AuthGuard('local') {"
can someone please help me to understand this?? and what is a best practice
That's just the thing, you don't have to create the
LocalAuthGuard. You really should only create it if youI think generally you're unaware of what is being called and how it's being called here. So, the
PassportStrategyclass is used to configure the passport middleware for a sepcific strategy type (in this case the strategy frompassport-localwhich takes inusernameandpasswordfrom the request body and calls them throughvalidate(actuallyverifyin passport's code)). TheAuthGuard()is how Nest abstracts the call topassport.use('strategy', (req, res, next))so that it fits better into the context of Nest.Normally when we use passport with express it looks like
This doesn't really fit into Nest's syntax and approach though using decorators to define the routes and not having middleware addable directly to the route handler.
So instead, Nest provides us the
PassportStrategymixin, which ends up callingpassport.use(new Strategy(this.validate.bind(this))(or very similar) under the hood, so that passport gets configured and is aware of the strategy and how to use it without us having to gunk up themain.ts.Now,
AuthGuard()takes in a strategy name and returns a guard class. This is a mixin as well, which is a function that returns a class. This guard has it's owncanActivateand ends up calling topassport.authenticate(strategy)for us, and handles the response that comes from passport, either allowing the guard toreturn trueand move on, or Nest willthrow new UnathorizedException()for us, to return a 401.Whether you use
class LocalAuthGuard extends AuthGuard('local')orAuthGuard('local'), the same thing is happening with regards to passport and theLocalStrategythat extends the passport strategy class.This article does a deep dive on passport and Nest in the first half if you'd like to go into a bit more depth