I run the php artisan make:auth command and I will explain step by step what I do after that to understand the scenario,
The thing is, these kind of scenarios may arise, and I don't want to see this error message, just logout after clicking logout, even if the session is expired.
Note: This issue is not because of not adding @csrf
To fix 419 page expired error in laravel, you have to use the CSRF token carefully in your project.
That being said, you can get a 419/page expired error for two reasons: The page takes too long to send its request and, as such, the token expires (page expired). You probably did not add the @csrf blade code with your form, so the token expected from your form is not present.
If you are using Laravel 5 builting auth mechanism then you will run AuthenticatesAndRegistersUsers trait getLogout() method which does $this->auth->logout(); Find this code edit the method like below for debugging. If you see the string "Logging out" then you must be logged out.
Well that's an obvious message you can maybe try to make a better layout for that page, but still it is good to show it so the user knows what happened. If you want to handle it differently you can try to redirect to the login page.
So in your app\Exceptions\Handler.php
file within the render method add this:
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->route('login');
}
A solution to the problem is relatively simple, and requires a small addition to the VerifyCsrfToken middleware;
use Closure;
public function handle($request, Closure $next)
{
if(!Auth::check() && $request->route()->named('logout')) {
$this->except[] = route('logout');
}
return parent::handle($request, $next);
}
Normally this file contains just an $except array of routes that should be ignored from csrf.
In this code we override the handle method and perform two checks.
If both are true then we add 'logout' to the except array. We then pass control to the core VerifyCsrfMiddleware which recognises the presence of the logout route in the array, and bypasses the check. The form data is correctly posted and we are redirected using the LogoutResponse.
The user sees no error page.
By checking in this way, we ensure that genuine logout requests are still protected by CSRF Token.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With