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-new\www\twicterminal.com\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken
.php : 191
/**
* Add the CSRF token to the response cookies.
*
* @param \Illuminate\Http\Request $request
* @param \Symfony\Component\HttpFoundation\Response $response
* @return \Symfony\Component\HttpFoundation\Response
*/
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.
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'));
});