Laravel 当我提交无效令牌时,中间件是 "bypassed",但当它是有效令牌时,中间件将被执行

Laravel middleware is "bypassed" when i submit the invalid token, but when it is a valid token, the middleware is executed

各位小伙伴们,我有一个问题。

Route::group([
    'middleware' => ['ensure.role:store', 'auth:api']
]

为了简化,

i have two roles : ADMIN and STORE

我创建了一个验证用户角色的中间件,如果用户角色正确,则允许用户访问路由。

它工作正常。 我尝试使用 ADMIN Jwt Token 访问 STORE 路由,我理所当然地被踢出局,反之亦然。

但是现在,如果我修改令牌,假设我向令牌的任何部分添加一个字符串,并尝试访问任何路由,实际上我被允许了。

我尝试了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 unauthenticated。

谢谢

我明白了。 经过一系列的测试和阅读,我发现在 laravel 5.3 之后,构造函数在中间件之前被调用。并且因为在我的构造函数中我在通过中间件进行身份验证之前使用了一个用户对象,所以我遇到了构造函数错误,因为用户为空。

当然在构造中使用用户对象是一种不好的做法,但是由于使用方便,我还是决定使用它。

使用基于闭包的中间件作为替代解决方案听起来很复杂

所以我使用了一种解决方法。

我创建了一个辅助函数,如果有用户对象或 return abort(401),我会 return 为真;如果没有用户对象,则将这一行添加到所有构造函数。

$this->checkAccess = EnsureRoleUtil::check('admin');

之后,我就照常做我的下一个构造函数

public function __construct() {
    $this->checkAccess = EnsureRoleUtil::check('admin');

    $this->user = Auth::user();
    $this->categoryM = new CategoryManager($this->user);
}

但是,需要注意的是,这不是一个好的做法,它只是一个 hack/workaround。