Search code examples
phplaravellaravel-5http-headersmiddleware

Laravel Middleware: Header may not contain more than a single header, new line detected


Laravel's Authenticate middleware gets the path users should be redirected to when they are not unauthenticated, and by default redirects users to /login. I want to implement an added functionality of redirecting the user with a message (such as session time of XYZ mins expired or kindly login to continue). So my Authenticate middleware looks like this:

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");
        }

    }

}

With or without $request->headers->set('Accept', 'application/json');, I keep getting this error: Header may not contain more than a single header, new line detected. Any ideas on how to resolve this?


Solution

  • With suggestions from @ourmandave and https://laracasts.com/discuss/channels/laravel/method-redirectto-with-a-flash-message, I learned that the redirectTo() wants to return the redirect route name, not actually redirect. So you should flash the 'message' to your session and then return the redirect '/login'. So I edited my code to look like this below, and it now works:

    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');
            }
    
        }
    
    }