nestjs 扩展了 jwt 保护

问题描述

为了检查用户表中是否存在用户,我扩展了 jwt 防护,这是我的代码

import {
  ExecutionContext,Injectable,UnauthorizedException,} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { error } from 'console';
import { UseRSService } from 'src/users/users.service';
import { Role } from './role.enum';
@Injectable()
export class JwtUserGuard extends AuthGuard('jwt') {
  constructor(private readonly userService: UseRSService) {
    super();
  }
  canActivate(context: ExecutionContext) {
    return super.canActivate(context);
  }

  handleRequest(err,user,info) {
    this.userService.findByEmail(user.email).then((user) => {
  if (user === undefined) {
    throw new UnauthorizedException();
  }
  return user;
}).catch(error=>{
  throw new UnauthorizedException();
});

    if (user.role !== Role.User) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

但我总是收到错误

(node:4504) UnhandledPromiseRejectionWarning: Error: Unauthorized
    at /media/ridwan/storage/workspace/backend/javascript/nestjs/queueing/dist/auth/jwt-user.guard.js:28:23
    at processticksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:4504) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection,use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:4504) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我的问题是如何处理 UnhandledPromiseRejectionWarning 即使用户不存在我的代码仍在运行?提前致谢..

解决方法

您通过使用承诺(带有链接的 thencatch)并且首先不返回承诺来混合同步和异步编程方法。我相信 Nest 的 handleRequest 方法不允许异步方法。所以发生的事情是你正在启动一个异步进程(对 this.userService.findByEmail 的承诺调用)并且它抛出一个错误,但你正在(同步)返回 user 属性(或抛出一个不同的错误处理得当)。然后,当承诺解决(拒绝)时,您有一个未处理的 throw,意思是 UnhandledPromiseRejection

我不明白为什么您不能在 Strategy 文件中执行所有这些逻辑,因为 handleRequest 发生在首先调用 validate 之后。

,

使用 PassportStrategy 混合并将 findByEmail 逻辑移到正确的位置。他们在这里解释了如何做到这一点:https://docs.nestjs.com/security/authentication#implement-protected-route-and-jwt-strategy-guards

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...