Home » Php » php – How to log out of an expired session in Laravel 5.x?

php – How to log out of an expired session in Laravel 5.x?

Posted by: admin July 12, 2020 Leave a comment


More recent versions of Laravel (correctly) use POST to logout of a session. The reasoning for this is that GET/HEAD should only be used for passive actions to be HTTP compliant.

POSTing with a csrf token also protects malicious users/sites from logging you out of your sessions:

However if the session has already timed out, and the user clicks logout (which triggers a POST to the logout route) a token mismatch error is received. It makes sense – the token doesn’t match, because the session has expired.

I can just catch that particular TokenMismatchException based on the request variables, and if so, continue them on their merry way (to the logged out redirect path, say “home” or “/”). Like this:

public function render($request, Exception $e)
    if ($e instanceof TokenMismatchException && $request->getRequestUri() === '/logout') {
        return redirect('/');

    return parent::render($request, $e);

My question is: if I do the above, what is the point of the token in the first place? And how to you logout a user when their session has expired while maintaining the intended outcomes of using a POST logout with a CSRF token?

How to&Answers:

For Laravel 5.7, see update below

The middleware that checks authentication should run before the middleware that checks the validity of the CSRF token.

That way, when the session has expired, you never get to the CSRF check in the first place because you have already checked for session expiration in the authentication middleware and done the redirect to the login page there.

This will not affect the CSRF protection of valid sessions logging out, because the valid session will make it through the authentication middleware.

By default, the Laravel middleware runs the CSRF check first. However, it should be easy to reorder them to work the other way.

For Laravel 5.7:

In Laravel 5.7, the Illuminate\Foundation\Http\Kernel class has a new field:

 * The priority-sorted list of middleware.
 * This forces non-global middleware to always be in the given order.
 * @var array
protected $middlewarePriority = [

Middleware classes that appear in this field are always run in the order in which they appear. The default setting for this field is shown above. (The Laravel starter project has only one change to this list: \App\Http\Middleware\Authenticate::class instead of \Illuminate\Auth\Middleware\Authenticate::class.)

If you add the CSRF middleware to the list (anywhere below the authentication middleware), that should ensure that it always runs in the order you want.