Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional authentication in Nest.js with @nestjs/passport

I have a route that needs to be used by authenticated and unauthenticated users. I use @UseGuards(AuthGuard('jwt')) to enable authentication but it prevents any unauthenticated user to access the route (normal).

How can I allow unauthenticated users to also access the route ?

It seems that there's no options that I can pass to AuthGuard in order to retrieve them in my passport strategy.

like image 371
Hugo Da Roit Avatar asked May 16 '19 16:05

Hugo Da Roit


People also ask

What is strategy in NestJS?

It is a way to define custom algorithm/logic to authenticate users. Passport has a lot of strategies like JWT, facebook, google and more.. You extend a strategy and add your custom logic like from where to get the user, how to validate the user and options passed to passport.

How does NestJS implement refresh token?

We need to create a method that will save the generated refresh_token in the database. Now we can handle the refresh token received and thus check if the token sent matches the one saved in the database, we can create our route to perform the refresh. Everything working!


Video Answer


1 Answers

You can just create your own AuthGuard for example by extending the existing one:

export class OptionalJwtAuthGuard extends AuthGuard('jwt') {

  // Override handleRequest so it never throws an error
  handleRequest(err, user, info, context) {
    return user;
  }

}

And then use this one on your controllers instead:

@UseGuards(OptionalJwtAuthGuard)
like image 139
Kim Kern Avatar answered Sep 17 '22 11:09

Kim Kern