【问题标题】:Laravel Middleware: Header may not contain more than a single header, new line detectedLaravel 中间件:标头可能不包含多个标头,检测到新行
【发布时间】:2019-04-12 10:35:54
【问题描述】:

Laravel 的 Authenticate 中间件获取用户在未经身份验证时应重定向到的路径,默认情况下将用户重定向到 /login。我想实现一个附加功能,用消息重定向用户(例如 XYZ 分钟的会话时间已过期或请登录以继续)。所以我的Authenticate 中间件看起来像这样:

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Exceptions\HttpResponseException;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if($request->is('api/*'))
        {
            throw new HttpResponseException(response()->error(['failure_reason'=>'Fresh Access Token Required'], 'Unauthorized Request', 401));  
        }

        if (!$request->expectsJson()) {
            // return route('login');
            $request->headers->set('Accept', 'application/json');
            return redirect("/login")->with("message", "Exceeded an inactivity period of over 15 mins. Kindly re-login to continue");
        }

    }

}

不管有没有$request->headers->set('Accept', 'application/json');,我总是收到这个错误:标题可能不包含多个标题,检测到新行。有关如何解决此问题的任何想法?

【问题讨论】:

  • redirectTo() 想要返回重定向路由名称,而不是实际重定向。因此,您应该将'message' 闪烁到您的会话中,然后返回重定向'/login'。请参阅此链接上的最佳答案。 laracasts.com/discuss/channels/laravel/…
  • 感谢@ourmandave,您的建议奏效了!

标签: php laravel laravel-5 http-headers middleware


【解决方案1】:

根据@ourmandave 和[https://laracasts.com/discuss/channels/laravel/method-redirectto-with-a-flash-message][2] 的建议,我了解到redirectTo() 想要返回重定向路由名称,而不是实际重定向。因此,您应该将“消息”闪烁到您的会话中,然后返回重定向“/登录”。所以我编辑了我的代码,如下所示,它现在可以工作了:

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Exceptions\HttpResponseException;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if($request->is('api/*'))
        {
            throw new HttpResponseException(response()->error(['failure_reason'=>'Fresh Access Token Required'], 'Unauthorized Request', 401));  
        }

        if (!$request->expectsJson()) {
            session()->flash('message', 'Exceeded an inactivity period of over 15 mins. Kindly re-login to continue'); 
            return route('login');
        }

    }

}  

【讨论】:

    猜你喜欢
    • 2017-06-20
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多