本文介绍了Nest.js中具有@ nestjs/passport的可选身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一条路由,需要经过身份验证和未经身份验证的用户使用.我使用@UseGuards(AuthGuard('jwt'))启用身份验证,但是它阻止了任何未经身份验证的用户访问路由(正常).

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 ?

似乎没有可以传递给AuthGuard的选项,以便在我的护照策略中进行检索.

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

推荐答案

您可以创建自己的 AuthGuard 例如,通过扩展现有的扩展名:

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)

这篇关于Nest.js中具有@ nestjs/passport的可选身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 16:03