【问题标题】:How to validate dto with class-validator before passing to passportjs AuthGuard如何在传递给 passportjs AuthGuard 之前使用类验证器验证 dto
【发布时间】:2022-12-30 19:20:01
【问题描述】:
如何在传递给护照 AuthGuard 之前使用类验证器验证 dto?我想使用类验证器来验证传入的 dto,但我看到“unathorized”而不是错误的请求异常,因为管道是在 nestjs 中的守卫之后进行评估的。我怎样才能改变这种行为,或者我必须在 auth guard 中验证 dto?
【问题讨论】:
标签:
nestjs
passport.js
nestjs-passport
【解决方案1】:
这不是 NestJS 的方式,但可能使用的唯一选项是验证 DTO 内部策略,你的守卫正在使用:
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-strategy';
import { validate } from 'class-validator';
import { BadRequestException } from '@nestjs/common';
class YourStrategy extends PassportStrategy(Strategy) {
authenticate(req, options) {
const errors = validate(req.body);
if (errors) {
throw new BadRequestException({ errors });
}
super.authenticate(req, options);
}
}