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

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


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 = [    \Illuminate\Session\Middleware\StartSession::class,    \Illuminate\View\Middleware\ShareErrorsFromSession::class,    \Illuminate\Auth\Middleware\Authenticate::class,    \Illuminate\Session\Middleware\AuthenticateSession::class,    \Illuminate\Routing\Middleware\SubstituteBindings::class,    \Illuminate\Auth\Middleware\Authorize::class,];

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.