如何解决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 即使用户不存在我的代码仍在运行?提前致谢..
解决方法
您通过使用承诺(带有链接的 then
和 catch
)并且首先不返回承诺来混合同步和异步编程方法。我相信 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。