In this blog, you will learn how to logout and redirect users to the login page when session timeout or session expired.
We can achieve same by many methods but most effective and easy method is using middleware.
While using middleware method to logout user on session expire, we need to specify user session expiry (when user expire), you can set any amount of time for this. In this method, practically we store time when user log in and then each time user request to access specific URLs then it check current time with last request time. If difference between both times greater then expiry time then it will force user to logout and redirect to login page.
Now let's assume your application perfectly working with authentication process. let's get started
So first of all, Open your terminal or command prompt, navigate to root directory of your project and run the following command:
php artisan make:middleware php artisan make:middleware SessionCheck
This command will create a middleware name php artisan make:middleware SessionCheck.php at app/Http/Middleware
In this step, we need to register our newly created middleware into kernel file. So, open app/Http directory and open file name Kernel.php and make 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 kernel as per you requirements like global, route specific or custom.
At last, we have to create our logic for check session is expired or not and if session is expired then we need to logout user. For that make 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 user navigate to other page or refresh current page then this logic check last activity time with current time and if last activity time is not in session then it will store it. If difference between last activity time and current time is less then expiry time then it will force user to logout otherwise it doesn't effect on user.
Here, you can set $timeout(expiry time) as per your requirements. Please note expiry time is in seconds.
start server using below command :
php artisan serve
Now open your browser put the below URL:
http://127.0.0.1:8000/
Ask anything about this examples