In this blog, you will learn how to log out and redirect users to the login page when a session timeout or session expired.
We can achieve the same by many methods but the most effective and easy method is using middleware.
While using the middleware method to log out the user on session expiration, we need to specify the user session expiry (when the user expires), you can set any amount of time for this. In this method, practically we store the time when the user logs in, and then each time the user request to access specific URLs then it checks the current time with the last request time. If the difference between both times is greater than the expiry time then it will force the user to log out and redirect to the login page.
Now let's assume your application working with an authentication process. let's get started
- Step 1: Create Middleware
- Step 2: Register the Middleware in the Kernel file
- Step 3: Logout Logic in Middleware
- Step 4: Running Our Application
So first of all, Open your terminal or command prompt, navigate to the root directory of your project, and run the following command:
This command will create a middleware name php artisan make:middleware SessionCheck.php at app/Http/Middleware.
Register the Middleware in the Kernel file
In this step, we need to register our newly created middleware into the kernel file. So, open app/Http directory and open the file name Kernel.php and make the following changes:
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\SessionCheck::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
You can register middleware into the kernel as per your requirements like global, route-specific or custom.
Logout Logic in Middleware
At last, we have to create our logic to check session is expired or not and if the session is expired then we need to logout the user. For that make the following changes into SessionCheck.php file :
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Session\Store;
use Auth;
use Session;
class SessionCheck
{
protected $session;
protected $timeout = 1000; //Session Expire time in seconds
public function __construct(Store $session){
$this->session = $session;
}
public function handle($request, Closure $next){
$isLoggedIn = $request->path() != 'dashboard/logout';
if(! session('lastActivityTime'))
$this->session->put('lastActivityTime', time());
elseif(time() - $this->session->get('lastActivityTime') > $this->timeout){
$this->session->forget('lastActivityTime');
$cookie = cookie('intend', $isLoggedIn ? url()->current() : 'dashboard');
Auth::logout();
}
$isLoggedIn ? $this->session->put('lastActivityTime', time()) : $this->session->forget('lastActivityTime');
return $next($request);
}
}
In this example code, when the user navigates to another page or refreshes the current page then this logic checks the last activity time with the current time and if the last activity time is not in session then it will store it. If the difference between the last activity time and the current time is less than the expiry time then it will force a user to log out otherwise it doesn't affect the user.
Here, you can set $timeout(expiry time) as per your requirements. Please note expiry time is in seconds.
Running Our Application
start server using the below command :
Now open your browser and put the below URL: