Optional authentication in Nest.js with @nestjs/passport

被刻印的时光 ゝ 提交于 2019-12-18 05:04:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!