Menu

Laravel Login To Only One Device System

Hello Guys,
Today we will learn how to log in and out from all other devices. For that, We need need to close other browser sessions. Mostly We need this system when we change the user password. Usually when we change the password. it changes the password. but we still kept logging in to the other browsers. For security reasons, we also need to log out from all different browsers. So, It will ask for the new password on the subsequent login request. So, It's better to keep only one device logged in for every user. This post will show you how to keep only one login session for user auth at a time.
This tutorial is divided into multiple steps.

Prerequisites

This tutorial is based on laravel 9. Laravel 9 has some minimum requirements.

  • PHP >=8.0.2
  • Composer
  • Apache/Nginx Server
  • Sublime Code Editor (Optional)
  • MySQL (version > 5)

Once, you have all this setup we can start by installing the laravel 9 projects.

Create a laravel project for a single-device login system. 

Let's start the first step, open the terminal/command prompt and run the following command.

composer create-project --prefer-dist laravel/laravel auth-tutorial

Once the laravel project is ready, We need to configure the database.

Create and Configure the database 

To configure the database, we can use the MySQL command prompt or PHPMyAdmin.

CREATE DATABASE auth_tutorial


Once we have a database, Let's connect our project to the database. For this, we need to configure the database in the .env file.
 


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=auth_tutorial
DB_USERNAME=root
DB_PASSWORD=

Once the database connection is ready. go to terminal/command-prompt and run the following command to create tables in the database.

php artisan migrate

After this command, It will create auth tables in the database like users, password_resets, and others.

Install the laravel UI package

For installing, laravel UI package run the following  composer command in the terminal/command prompt.

composer require laravel/ui

 It may take 1-2 minutes for installation. Once it has been done we need to install Auth Bootstrap Auth Scaffolding. For this run the following artisan command.

php artisan ui bootstrap --auth

After adding the auth Scaffolding. we need to compile the scaffolding js and CSS file by running the following command.
 

npm install && npm run dev

Once the UI assets are compiled our project home page will look like the below.

  

In the browser, the default homepage will be showing with Login and Register options.
 

Add Web Middleware For Authentication Session

Let's add laravel core middleware AuthenticateSession in middleware. For this navigate to the app/http folder and open the kernel.php file in the editor. Now add 

\Illuminate\Session\Middleware\AuthenticateSession::class middleware to web array available in $middlewareGroups array. 

 protected $middlewareGroups = [
        'web' => [
            ...

            ...
            ...
            ...
            \Illuminate\Session\Middleware\AuthenticateSession::class
        ],

        'api' => [
            ...

            ...
            ...
            ...
        ],
    ];

After adding the middleware, It will look like this.

 /**
     * 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\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \Illuminate\Session\Middleware\AuthenticateSession::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

So, Our middleware is added now, We can add the single auth login functionality now.
 

Add Functionality login to only one device

 

We all know Laravel Auth provides us with default controllers for managing the user auth system. So here, we have the Auth folders inside the Controllers folder. Open the LoginController file, and here you have to check if the user is authenticated then will log out the user from other login sessions. It will invalidate other browser sessions and keep only the current sessions.

For this, we will use the authenticated() method provided by the Laravel auth core package.

 /**
 * Function Authenticated users
 * @param request
 */
 protected function authenticated(Request $request)
 {
     Auth::logoutOtherDevices($request->password);
 }

This function/method will check the current password which is for the login attempts as a parameter. It will verify the authentication and invalidate other sessions from the different browsers/sessions.

After implementing this function in the Laravel LoginController, the LoginController will look like the below.


namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide the functionality to your applications.
    |
    */
    
    use AuthenticatesUsers;
    
    /**
    * Where to redirect users after login.
    *
    * @var string
    */
    protected $redirectTo = RouteServiceProvider::HOME;
    
    /**
    * Create a new controller instance.
    *
    * @return void
    */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
    
    
    /**
    * Function Authenticated users
    * @param request
    */
    protected function authenticated(Request $request)
    {
        Auth::logoutOtherDevices($request->password);
    }
}

Finally, all the steps are complete. Now you can try the code by login into the 2 different browsers.
If you need the full code you can download or clone it from my GitHub profile. GitHub Repo

Hope you like this tutorial. Please this post with your friends.
Share your comment and quotes below.

Thanks

1585
Search

Ads