Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mostromhall's avatar

CSRF Token Mismatch on logout when session has expired but still authenticated due to remember_token

Hi all, hopefully someone can help please.

I am encountering an issue where I get a 419 token mismatch on logout when the ordinary 2 hour session has expired but I am still authenticated as I logged in with remember me selected. This is not occurring if I have not selected remember me as I have the below check in the VerifyCsrfToken middleware.

if (!auth()->check() && $request->route()->named('logout')) {
        $this->except[] = route('logout');
    }

    return parent::handle($request, $next);

This does not catch the logout request when there this a remember token cookie as auth()->check() is returning true. Does anyone have any ideas what could be causing this? Thanks in advance!

0 likes
7 replies
mostromhall's avatar

Thanks for responding, your post is where I got the above from :)

Yeah that's what I found, is it possible to check if a users session has expired but they're still logged in due to the remember token?

Snapey's avatar

@somethingbig i'll try and resolve it this morning. I think there is an attribute viaRemember somewhere that tells you if they were automatically logged in

Snapey's avatar
Snapey
Best Answer
Level 122

Please can you try this variant. If its ok, then I'll update the post. It seems to work in my testing.

class VerifyCsrfToken extends Middleware
{
    public function handle($request, Closure $next)
    {
        if($request->route()->named('logout')) {

            if (!Auth::check() || Auth::guard()->viaRemember()) {

                $this->except[] = route('logout');
                
            }   

        }

        return parent::handle($request, $next);
    }
}

viaRemember() is only true for the very first request cycle. So the code ignores all requests that are not for logout, and then adds logout to the except list if the user is not authenticated OR they just logged in with viaRemember()

Snapey's avatar

Small amendment. Still need the except array declaring

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
use Illuminate\Support\Facades\Auth;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
    
    public function handle($request, Closure $next)
    {
        if($request->route()->named('logout')) {

            if (!Auth::check() || Auth::guard()->viaRemember()) {

                $this->except[] = route('logout');

            }   

        }

        return parent::handle($request, $next);
    }
}

1 like

Please or to participate in this conversation.