NestJs-无法在RolesGuard中获取用户上下文 [英] NestJs - Unable to get user context in RolesGuard

查看:242
本文介绍了NestJs-无法在RolesGuard中获取用户上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将NestJS用作客户端API的框架.在框架内,我们使用的是相当不错的标准Passport/JWT auth基础结构.找到承载令牌后,我们的AuthGuard将触发,在安全的API端点中,我可以通过'@Res()request'注入HTTP上下文,并访问包含我的Jwt令牌有效负载的'request.user'属性

I'm using NestJS as the framework for a client API. Within the framework we are using a pretty standard Passport/JWT auth infrastructure that is working fine. Our AuthGuard is firing when the bearer token is found and, in secure API endpoints, I can inject the HTTP context via '@Res() request' and get access to the 'request.user' property which contains the payload of my Jwt token.

最重要的是,我们试图以与文档中提供的示例代码以及GitHub上的一些示例项目(没有一个实际上使用此防护,但实际上包含此防护)提供的示例代码非常相似的方式实现"RolesGuard".样本守卫).

On top of this we are attempting to implement a 'RolesGuard' in a very similar fashion to the sample code provided in the documentation and some of the sample projects on GitHub (none of which actually use this guard but they include it as a sample guard).

我们的问题是我们的AuthGuard会触发并验证Jwt令牌,然后我们的RolesGuard会触发,但是传递给它的请求对象没有附加到该请求的用户元数据.

Our issue is that our AuthGuard fires and validates the Jwt token and THEN our RolesGuard fires but the request object it is passed does not have the user meta-data attached to the request.

RolesGuard中的关键代码是:

The key code in our RolesGuard is:

    const request = context.switchToHttp().getRequest();
    const user = request.user;

    if (!user) {
        return false;
    }

在上面的片段中,用户始终是错误的.是否有人在Nest中编写了基于角色/权限的防护措施,从而成功访问了当前用户的作用域?所有代码均已触发,所有内容均显示正确.

In the above snipped the user is always false. Has anyone written a role/permission based guard in Nest that successfully gets access to the scope of the current user? All the code is firing and everything appears registered correctly.

-凯文

推荐答案

最终,这似乎是守卫的排序问题,而且看起来不容易解决(没有框架允许对排序进行某些控制) ).

Ultimately this appears to be an ordering issue with the guards and it doesn't look like it can be easily resolved (without the framework allowing some control over the ordering).

我希望在全球范围内注册RolesGuard,但这会导致它先注册然后首先启动.

My hope was to register the RolesGuard globally but that causes it to be registered first and fire first.

@UseGuards(AuthGuard('jwt'), RolesGuard)
@Roles('admin')

如果我在端点级别注册它,然后将其放在AuthGuard之后,则它会第二次触发,并且我会在Guard自身中获得期望的用户上下文.它不是完美的,但可以.

If I register it at the endpoint level and put it after the AuthGuard then it fires second and I get the user context I am expecting within the guard itself. It isn't perfect but it works.

-凯文

这篇关于NestJs-无法在RolesGuard中获取用户上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆