One of my old answers on SO: https://stackoverflow.com/a/57095026/1457270
how to redirect to login page when 419 error
Hi.
How can I redirect to another route ( login ) when 419 error happens ?
Thanks for reply.
But I need error handler in laravel 8 . not previous version.
Thanks.
@binggle this worked for me on Laravel 8:
in your App\Exceptions\Handler.php class, within the register() method, add the following:
$this->renderable(function (\Exception $e) {
if ($e->getPrevious() instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->route('login');
};
});
Thanks.. I will try.
I would not redirect to the login page. 419 only means the csrf token is invalid, so a new login isn't required. Why not just do a
back()
->withInput(request()->except('_token'))
->withError('Invalid token. Please submit the form again');
Actually 419 error happens even when user logout.
'logout' uses csrf token too..
And usual form submit requires csrf token too.
So it is everywhere, and that's why I want to customize error handler.
Thanks.
@binggle No. Like previously mentioned, you get a 419 error when the CSRF token has expired. It does not mean the user’s session has expired.
If you try and redirect a user to the login page when they’re actually still logged in, then you’re going to end in a redirect loop.
You gave me the important point..
I must not redirect to 'login' route for the shake of CSRF Token.
Yep. Thank you so much.
@binggle make sure your session is persisting (working), you shouldn't be getting a 419 on logout unless something was modified.
Logout uses a form that's submitted with plain javascript.
<form method="POST" action="{{ route('logout') }}">
@csrf
<x-responsive-nav-link href="{{ route('logout') }}"
onclick="event.preventDefault();
this.closest('form').submit();">
{{ __('Logout') }}
</x-responsive-nav-link>
</form>
Also make sure you didn't change something, and check session by setting something like this is a test in session, go to another page and see if you can get that test from session.
I have some tips on preventing csrf issues
https://talltips.novate.co.uk/laravel/csrf-and-expired-login-forms
and
https://talltips.novate.co.uk/laravel/csrf-and-expired-logout-forms
I often encounter this issue when leaving a form idle for too long, so I created a package to handle this https://github.com/devtical/laravel-drunk-on-419/
Please or to participate in this conversation.