skip to Main Content

I am using Laravel 9.41.0 and PHP 8.1. When Laravel’s default session timeouts, accessing any protected routes after that throws this exception. Laravel is not redirecting to login route which I have already defined. The exception occurs in VerifyCsrfToken middleware. Here is the method where exception occurs:

C:wamp-newwwwtwicterminal.comvendorlaravelframeworksrcIlluminateFoundationHttpMiddlewareVerifyCsrfToken

.php

: 191

/**

 * Add the CSRF token to the response cookies.

 *

 * @param  IlluminateHttpRequest  $request

 * @param  SymfonyComponentHttpFoundationResponse  $response

 * @return SymfonyComponentHttpFoundationResponse

 */

protected function addCookieToResponse($request, $response)

{

    $config = config('session');



    if ($response instanceof Responsable) {

        $response = $response->toResponse($request);

    }



    $response->headers->setCookie($this->newCookie($request, $config));



    return $response;

}

This line in the method: $response->headers->setCookie($this->newCookie($request, $config)); is where the exception emerges from.

I googled this issue a lot but haven’t find any working solution yet. There are similar questions here on StackOverflow their scenarios, origin and use cases are different. Their solutions didn’t work for me either.

Note: This exception occurs only for default auth middleware protected routes after default session timeouts.

2

Answers


  1. Chosen as BEST ANSWER

    Thank you everyone. I love the community and it's amazing helping each other.

    I did extensive search and none of the solution worked for me. Luckily, I sorted out the problem by myself but forgot to add the answer here. Previously, I had changed the Laravel's default Handler class (for handling exceptions) and had added this method for an unauthenticated API request. It worked fine for API calls but web requests were having issues. Here is the method:

    protected function unauthenticated($request, AuthenticationException $exception)
        {
            if ($request->expectsJson()) {
                return $this->response('User not authenticated. Access denied.', Response::HTTP_FORBIDDEN);
            }
            
        }
    

    What I forgot to add was this line at the end of the method and this was the reason why $response object was null. Now it works fine.

    return redirect()->guest($exception->redirectTo() ?? route('login'));
    

    PS:- Later I found a more elegant solution. Something that was the "Laravel's way" of doing stuff. I called the renderable method of the exception class inside register method of Handler class and caught the AuthenticationException exception. Here is a look:

    $this->renderable(function (AuthenticationException $e, $request) {
                if ($request->is('api/*')) {
                    return  $this->response("User not authenticated. Access denied.",
                     Response::HTTP_FORBIDDEN);
                }
                return redirect()->guest($e->redirectTo() ?? route('login'));
            });
    

  2. For each class in your app/Http/Middleware folder, check each handle method and make sure that each one always returns an instance of IlluminateHttpResponse. You said that you have no custom middleware and didn’t modify any of the middleware classes that Laravel gave you. Check them closely. Somewhere you are ending up with a null $response variable that is supposed to be an instance of IlluminateHttpResponse. The most likely cause is a handle method not returning a value directly (thus returning null).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search