所有我的朋友们,我有一个问题。
Route::group([
'middleware' => ['ensure.role:store', 'auth:api']
]
为了简化,
i have two roles : ADMIN and STORE
我已经创建了一个中间件,它将验证用户角色,如果用户角色正确,那么将允许用户访问路由。
它工作得很好。我尝试使用ADMIN Jwt令牌访问存储路由,我理所当然地被踢出去了,反之亦然。
但是现在,如果我修改了令牌,假设我向令牌的任何部分添加了一个字符串,并尝试访问任何路由,实际上我是被允许这样做的。
我尝试了var_dump并在相关的中间件上打印了一些东西,下面是我的观察结果。
1. If the token is VALID as one of the user role, then
the var_dump is executed, (means the middleware is executed)
2. if the token is INVALID as in i add / modify the original
token, then the var_dump is not executed, and so are the
others route middleware.
我想知道是什么导致了这种行为,以及这个问题的修复方法是什么,因为在任何令牌无效的情况下,我都需要抛出401未认证的异常。
谢谢
发布于 2019-01-30 17:57:40
我想通了。经过一系列的测试和阅读,我发现在laravel 5.3和更高版本中,构造函数是在中间件之前调用的。而且因为在我的构造函数中,我在被中间件验证之前使用了一个user对象,所以我遇到了构造函数错误,因为user为空。
当然,在构造中使用user对象是一种不好的做法,但是由于使用方便,我还是决定使用它。
使用基于闭包的中间件作为替代解决方案听起来很复杂
因此,我使用了一种变通方法来解决此问题。
我创建了一个助手函数,如果有user对象,则返回true,如果没有user对象,则返回abort(401);如果没有user对象,则将这一行添加到所有构造函数中。
$this->checkAccess = EnsureRoleUtil::check('admin');
在此之后,我只需像往常一样执行下一个构造函数
public function __construct() {
$this->checkAccess = EnsureRoleUtil::check('admin');
$this->user = Auth::user();
$this->categoryM = new CategoryManager($this->user);
}
然而,需要注意的是,这不是一个好的实践,它只是一个技巧/变通方法。
https://stackoverflow.com/questions/54444047
复制