Summer sale! Save 50% on access to our entire library of courses.Join here →

Logging Users Out of Other Browser Sessions with Laravel

July 19th, 2024

Laravel provides a method for logging users out of all other browser sessions by re-hashing passwords. Let's look at how to use it to invalidate all other browser sessions for your users.

Here's a quick rundown of how logging users out of other sessions works in Laravel.

The first step is to apply the AuthenticateSession middleware globally or to specific routes.

Here's what that looks like using route grouping:

Route::middleware(['auth', 'auth.session'])->group(function () {
    // Your routes
});

If you want to apply this middleware to all routes, open up your bootstrap/app.php file and add the middleware within the withMiddleware closure:

use Illuminate\Session\Middleware\AuthenticateSession;

->withMiddleware(function (Middleware $middleware) {
     $middleware->append(AuthenticateSession::class);
})

Once that's done, you can simply use the logoutOtherDevices method to re-hash the user's password (it won't change it), invalidating all other sessions the user is logged into.

auth()->logoutOtherDevices($password);

$password refers to the current user's password, which you'll need to accept into a form (in plain text) and pass to this method.

Let's look at a working example with validation to demonstrate how you might implement this.

After you've added the AuthenticateSession middleware globally or within a route group, create a controller to handle the entry and process of logging users out of all other sessions.

php artisan make:controller DeviceSessionController
class DeviceSessionController extends Controller
{
    public function index()
    {
        return view('session.index');
    }

    public function destroy()
    {
        //
    }
}

Add the routes for these, too:

Route::get('/session', [DeviceSessionController::class, 'index'])
    ->middleware(['auth'])
    ->name('session.index');

Route::delete('/session', [DeviceSessionController::class, 'destroy'])
    ->middleware(['auth'])
    ->name('session.destroy');

Make a view to serve the password prompt for the user.

php artisan make:view session.index

In the session/index.blade.php view, you just need a form where the user can enter their password.

<form action="{{ route('session.destroy') }}" method="post">
    @csrf
    @method('DELETE')

    <div>
        <label for="password">Confirm your password</label>
        <div>
            <input type="password" name="password" id="password" />
            @error('password')
                <div>{{ $message }}</div>
            @enderror
        </div>
    </div>

    <button type="submit">Log out of other devices</button>
</form>

Once this is submitting through, add the validation rules and logoutOtherDevices method to the destroy method in your controller.

class DeviceSessionController extends Controller
{
    public function index()
    {
        return view('session.index');
    }

    public function destroy(Request $request)
    {
        $request->validate(['password' => 'required|current_password']);

        auth()->logoutOtherDevices($request->password);

        return redirect()->back();
    }
}

This validates the user's password to confirm it matches their current password, then destroys all other browser sessions before redirecting back. Feel free to add a flash message here or redirect to another page.

And that's a super simple way to log users out of other devices with Laravel.

Thanks for reading! If you found this article helpful, you might enjoy our practical screencasts too.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first to leave a comment.