【问题标题】:Return 403 if route is not allowed如果路由不被允许返回 403
【发布时间】:2023-03-19 09:25:01
【问题描述】:

我有带有中间件的路由组(我使用Zizaco/entrust 包):

Route::group(['as' => 'admin.', 'prefix' => 'admin', 'middleware' => ['role:admin']], function (){
    ...
});

当我尝试在未经身份验证的情况下输入 http://mysite/admin 时出现异常

Symfony\Component\HttpKernel\Exception\HttpException
没有消息

但我想返回 403。
我试着这样做:

Route::fallback(function(){
    abort(403);
});

但它没有帮助。


编辑 1:我们在 Laravel 5.5.28 中有 exception handle

public function abort($code, $message = '', array $headers = [])
    {
        if ($code == 404) {
            throw new NotFoundHttpException($message);
        }

        throw new HttpException($code, $message, null, $headers);
    }

如您所见,没有403 句柄。

【问题讨论】:

  • 404 未找到
  • @kerbholz 谢谢,我已经改进了我的问题

标签: php laravel-5.5


【解决方案1】:

你要修改handle 角色中间件的方法

public function handle($request, Closure $next, $roles)
{
    if (!is_array($roles)) {
        $roles = explode(self::DELIMITER, $roles);
    }
    if ($this->auth->guest() || !$request->user()->hasRole($roles)) {
        abort(403); // notice here it returns 403
    }
    return $next($request);
}

【讨论】:

  • Undefined class constant 'DELIMITER'
  • 顺便说一句,我将403 更改为404,并按预期得到404。但是为什么 Laravel 不处理 403 比呢?
  • const DELIMITER = '|';
  • @DoIGetAnything 请在您的错误视图中有 403 页
猜你喜欢
  • 2018-01-23
  • 2015-09-06
  • 2016-03-29
  • 2013-03-29
  • 1970-01-01
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多