问题
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.
回答1:
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)
来源:https://stackoverflow.com/questions/56173298/optional-authentication-in-nest-js-with-nestjs-passport