Implement Secure SSO with OAuth2 in Laravel 11

Websolutionstuff | Oct-16-2024 | Categories : Laravel

Hello, laravel web developers! In this tutorial, I'll show you how to implement a secure Single Sign-On (SSO) system in Laravel 11 using OAuth2. Whether you're integrating third-party providers like Google or Microsoft, or building your internal SSO system.

This step-by-step guide will make the process easy to follow. With SSO, users can log in to your Laravel application using a single set of credentials, improving security and user experience.

Implement Secure SSO with OAuth2 in Laravel 11

Implement Secure SSO with OAuth2 in Laravel 11

 

Step 1: Install Laravel and Socialite

First, we'll need to install Laravel 11 and the laravel/socialite package, which provides OAuth2 integration for popular services.

composer create-project --prefer-dist laravel/laravel sso-example
cd sso-example
composer require laravel/socialite

 

Step 2: Set Up Google OAuth2

To set up SSO with Google, you'll need to register your application in the Google Developers Console. After registering, get the client_id and client_secret

Add the credentials to your env file.

GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REDIRECT_URL=http://your-app-url.com/auth/google/callback

Update config/services.php with the Google configuration.

'google' => [
    'client_id' => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect' => env('GOOGLE_REDIRECT_URL'),
],

 

Step 3: Create Routes and Controller for Google SSO

Add routes in the routes/web.php file.

use App\Http\Controllers\Auth\OAuthController;

Route::get('auth/google', [OAuthController::class, 'redirectToGoogle'])->name('google.login');
Route::get('auth/google/callback', [OAuthController::class, 'handleGoogleCallback']);

Now, create a controller to handle the Google OAuth2 login process:

php artisan make:controller Auth/OAuthController

In OAuthController.php, add the following methods:

namespace App\Http\Controllers\Auth;

use Laravel\Socialite\Facades\Socialite;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\RedirectResponse;

class OAuthController extends Controller
{
    public function redirectToGoogle(): RedirectResponse
    {
        return Socialite::driver('google')->redirect();
    }

    public function handleGoogleCallback(): RedirectResponse
    {
        $user = Socialite::driver('google')->stateless()->user();

        // Find or create the user in your database
        $existingUser = User::where('email', $user->getEmail())->first();

        if ($existingUser) {
            Auth::login($existingUser);
        } else {
            $newUser = User::create([
                'name' => $user->getName(),
                'email' => $user->getEmail(),
                'google_id' => $user->getId(),
                // Other user fields...
            ]);

            Auth::login($newUser);
        }

        return redirect()->intended('/home');
    }
}

 

Step 4: Set Up Microsoft OAuth2 (Optional)

For Microsoft SSO, you need to register your app on Azure Active Directory

Add your Microsoft OAuth2 credentials to the env file.

MICROSOFT_CLIENT_ID=your-microsoft-client-id
MICROSOFT_CLIENT_SECRET=your-microsoft-client-secret
MICROSOFT_REDIRECT_URL=http://your-app-url.com/auth/microsoft/callback

Update config/services.php with the Microsoft configuration.

'microsoft' => [
    'client_id' => env('MICROSOFT_CLIENT_ID'),
    'client_secret' => env('MICROSOFT_CLIENT_SECRET'),
    'redirect' => env('MICROSOFT_REDIRECT_URL'),
],

In OAuthController.php, add similar methods for Microsoft.

public function redirectToMicrosoft(): RedirectResponse
{
    return Socialite::driver('microsoft')->redirect();
}

public function handleMicrosoftCallback(): RedirectResponse
{
    $user = Socialite::driver('microsoft')->stateless()->user();
    // Similar user handling as Google
}

Add the necessary routes in routes/web.php

Route::get('auth/microsoft', [OAuthController::class, 'redirectToMicrosoft'])->name('microsoft.login');
Route::get('auth/microsoft/callback', [OAuthController::class, 'handleMicrosoftCallback']);

 

Step 5: Build an Internal SSO System (Optional)

If you're building an internal SSO system, you can implement OAuth2 using Laravel Passport. First, install Passport.

composer require laravel/passport
php artisan passport:install

Configure Passport in config/auth.php

'guards' => [
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Next, follow the Laravel Passport documentation to create and manage OAuth2 tokens.

 

Step 6: Securing the Application

To enhance security, make sure to:

  • Use HTTPS for the OAuth2 callbacks.
  • Set up CSRF protection for authentication routes.
  • Regularly update your OAuth2 credentials and rotate secrets when needed.

 


You might also like:

Recommended Post
Featured Post
Laravel 8 Autocomplete Search from Database
Laravel 8 Autocomplete Search...

In this article, we will see the laravel 8 autocomplete search from the database. Using ajax autocomplete...

Read More

Mar-01-2021

Laravel mix is not recognized as an internal or external command
Laravel mix is not recognized...

Greetings, developers! If you've encountered the frustrating "Laravel Mix is not recognized as an internal...

Read More

Dec-29-2023

Vue Js Sweetalert Modal Notification Tutorial
Vue Js Sweetalert Modal Notifi...

In this example, we will see vue js sweetalert modal notification tutorial. vue.js wrapper for sweetalert2. with su...

Read More

Jan-12-2022

How to Install Jenkins on Ubuntu
How to Install Jenkins on Ubun...

In today's fast-paced software development landscape, I've understood the significance of continuous integration...

Read More

Aug-07-2023