首页 > 解决方案 > 如果用户在 laravel 6 中通过身份验证,则显示不同的 http 错误页面

问题描述

我正在编写一个具有控制面板的应用程序。我想在用户登录的情况下将控制面板的 chrome 保留在 404 和 403 页面中。但是Auth::user()总是auth()->id()返回nullapp/Exceptions/Handler.php显然刀片指令也不能按预期工作(用户似乎总是被注销)

做了一些研究,这似乎是因为未加载 StartSession 中间件。解决该问题的一种方法似乎是全局启用中间件,但这会导致 API 路由存在潜在的安全问题。

所以我的问题是如何将中间件添加到 Handler.php?定义构造函数似乎确实有效。然而,在控制器中调用 $this->middleware() 不会。也许还有其他一些用于加载中间件的语法

标签: laravelauthenticationmiddlewarelaravel-6laravel-authentication

解决方案


感谢 github 上的这个帖子: https ://github.com/laravel/framework/issues/17187 ,特别是 ssddanbrown 和 DominusVilicus 的评论,我想通了。但主要是[ssddanbrown对Bookstack的提交][1]我只改了一个文件app/Exceptions/Handler.php

我添加了

use Illuminate\Http\Request;
use Illuminate\Pipeline\Pipeline;

上课之前。创建了以下方法:

/**
* Load Session middleware then run the callback closure and return its result 
*
* @param  \Illuminate\Http\Request $request
* @param  \Closure $callback
* @return \Illuminate\Http\Response
*/
protected function loadSessionMiddleware(Request $request, \Closure $callback)
{
    $pipe = new Pipeline($this->container);

    $middleware = [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    ];

    return $pipe->send($request)->through($middleware)->then($callback);
}

并修改了渲染方法:

public function render($request, Exception $exception)
{
    if (
        // Only process non API requests' ...
        $request->segment(1) !== 'api' &&
        // ... HTTP exceptions with ...
        $this->isHttpException($exception)
    ) {

        $code = $exception->getStatusCode();
        // ... codes between 400 and 599
        if ($code >= 400 && $code < 600) {

            return $this->loadSessionMiddleware(
                $request,
                function ($request) use ($exception, $code) {

                    // Load error names and descriptions from language files
                    $name = __('http-errors.' . $code . 'n');
                    $desc = __('http-errors.' . $code . 'd');

                    // Display the error page
                    return response()->view(
                        'errors.http',
                        compact('code', 'name', 'desc'),
                        $code
                    );
                }
            );
        }
    }
    return parent::render($request, $exception);

现在,在此之后,@auth@guest刀片指令在模板中按预期工作。

. .

注意:我使用单个视图模板和语言文件来呈现多个错误页面,因为我希望必须本地化我的项目,但是如果您只想将中间件添加到 404,您的回调函数和条件的内容可能会稍微简单一些页。更重要的是,这部分代码实际上并没有完全完成它的使命,因为并非所有产生 HTTP 代码 400-599 响应的异常都是 HTTPException 的实例,特别是:AuthorizationException 和 AuthenticationException。


推荐阅读