javascript - 在 NestJs 中何时使用守卫以及何时使用中间件
问题描述
我想创建一个 NestJs 应用程序,并希望有一个中间件验证请求对象中的令牌,以及一个身份验证保护来验证令牌有效负载中的用户。
通过拆分这个,我希望有一个干净的分离。首先我的中间件
@Injectable()
export class TokenMiddleware implements NestMiddleware {
use(req: any, res: Response, next: NextFunction) {
try {
const headers: IncomingHttpHeaders = req.headers;
const authorization: string = headers.authorization;
const bearerToken: string[] = authorization.split(' ');
const token: string = bearerToken[1];
// !! Check if token was invalidated !!
req.token = token;
req.tokenPayload = verifyToken(token);
next();
} catch (error) {
throw new UnauthorizedException();
}
}
}
它仅验证令牌并使用编码令牌及其有效负载扩展请求对象。我的授权守卫
@Injectable()
export class AuthenticationGuard implements CanActivate {
constructor(private readonly usersService: UsersService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request: any = context.switchToHttp().getRequest();
try {
const user: any = request.tokenPayload;
if (!user) {
throw new Error();
}
const findByIdDTO: FindByIdDTO = { id: user.id };
const existingUser: UserRO = await this.usersService.findById(findByIdDTO);
if (!existingUser) {
throw new Error();
}
// attach the user to the request object?
return true;
} catch (error) {
throw new UnauthorizedException();
}
}
}
该守卫检查令牌有效负载中提供的用户是否是有效用户。如果一切正常,我应该在哪里将用户附加到请求对象?据我所知,警卫只检查某事是否正确。但我不想将所有这些逻辑保留在令牌中间件中。在 auth guard 中完成验证后,我可以在哪里将数据库用户附加到请求中?
解决方案
如果你想做类似于 Passport 的事情,你总是可以将用户附加到req.user
,这在 Node.JS 世界中被视为非常标准的设置。
对你的一个附带问题:有什么理由不让两个守卫一个接一个地发挥作用?让一名警卫检查令牌是否存在并且确实是有效的令牌,而一名用于验证令牌上的用户确实是有效的。这样你就不用使用中间件(主要是为了兼容性而包括在内)并且仍然有分离的逻辑。
推荐阅读
- tinymce - TinyMCE 在调用 execCommand 时抢了焦点
- android - MissingPluginException(在通道尝试中找不到方法显示的实现)
- floating-point - ieee754浮点异常有什么用?(NAN,OVERFLOW,INEXACT,UNDERFLOW,DIV0)
- c - 初学者试图在 MS VS Code 中调试一个简单的 C 程序,但每当我尝试使用调试器时,就会出现问题
- c - lua源码问题,""s的用法
- python - 将列表转换为 str 并写入新的 .mtx 文件
- r - kableExtra addfootnote 一般跨越多行与 PDF (LaTeX) 输出
- python - 非二次二维矩阵的插值
- c# - 使用实体框架和批量更新获取错误“无效的列名”
- python - 使用 Python 抓取以在 Wordpress 上发布 (XML-RPC)