[英]Can I negate NestJS's Guard?
I have AuthGuard
from @nestjs/passport
used on one my method (route) like this:我有
AuthGuard
从@nestjs/passport
像这样的一个我的方法(路线)上使用的:
@UseGuards(AuthGuard('jwt'))
@Get('profile')
getProfile(@Req() req) {
return this.userService.findOne(req.user.id);
}
Can I negate this guard, so only users without JWT can go trough ?我可以否定这个守卫,所以只有没有 JWT 的用户才能通过吗? I do not want users with JWT in header to access login/register route accidentally.
我不希望标头中有 JWT 的用户意外访问登录/注册路由。
As bashleigh said in her comment, you can create your own guard that checks for a jwt and rejects if it comes in. A simple example could be something like正如 bashleigh 在她的评论中所说,你可以创建自己的守卫来检查 jwt 并拒绝它进来。一个简单的例子可能是这样的
@Injectable()
export class NoJwtGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const req = context.switchToHttp().getRequest();
const auth = req.headers['Authroization'];
// as you should not have any authorization headers you an reject if the header exists
return !auth;
}
}
While it isn't possible to immediately negate a built in guard, you could also extend the AuthGuard('jwt')
and then in your custom implementation of canActivate
you could return !super.canActivate(context)
虽然不可能立即否定内置的守卫,但您也可以扩展
AuthGuard('jwt')
然后在您自定义的canActivate
实现中您可以return !super.canActivate(context)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.