惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
博客园 - 三生石上(FineUI控件)
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
V
Visual Studio Blog
小众软件
小众软件
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MongoDB | Blog
MongoDB | Blog
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
The Cloudflare Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Engineering at Meta
Engineering at Meta
L
LangChain Blog
Martin Fowler
Martin Fowler
GbyAI
GbyAI
博客园 - 司徒正美

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Implement SAML SSO Authentication in Laravel Filament wit...
yebor974 · 2026-05-20 · via DEV Community

Single Sign-On (SSO) is a common requirement in enterprise applications.

When working with Laravel Filament in internal business environments, clients often want to authenticate users directly through:

  • Active Directory
  • Microsoft Entra ID (Azure AD)
  • Okta
  • Keycloak
  • Google Workspace

Instead of managing passwords inside your application.

In this article, we’ll build a clean SAML SSO integration using:

  • Laravel Socialite
  • The Socialite SAML2 provider

The goal is not only to make authentication work, but also to build a maintainable foundation for enterprise environments.

At the end of this article, you’ll have:

  • SAML authentication working inside Filament
  • A metadata endpoint for your Identity Provider
  • A dedicated authentication flow
  • A clean architecture ready for role synchronization

In the premium follow-up article, we’ll implement:

  • Active Directory group mapping
  • Spatie Permission synchronization
  • Production-ready role handling
  • Enterprise access control strategies

Installing the SAML2 Provider

First, install Laravel Socialite and the SAML2 provider:

composer require laravel/socialite
composer require socialiteproviders/saml2

Enter fullscreen mode Exit fullscreen mode

You can then configure your SAML provider inside config/services.php.

Configuring the SAML Provider

Here is a simple SAML configuration:

'saml2' => [
    'metadata' => env('SAML2_METADATA_URL', 'http://localhost:4000/api/saml/metadata'),
    'sp_acs' => 'auth/saml2/callback',
    'sp_default_binding_method' => \LightSaml\SamlConstants::BINDING_SAML2_HTTP_POST,
    'sp_name_id_format' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified',
],

Enter fullscreen mode Exit fullscreen mode

Depending on your security requirements, you may also need signed or encrypted assertions.

Understanding the Configuration

metadata

This is the Identity Provider metadata URL.

Depending on your environment, this could come from:

  • Microsoft Entra ID
  • Okta
  • Keycloak
  • A local SAML testing provider

The provider uses this metadata to retrieve:

  • certificates
  • SSO endpoints
  • bindings
  • entity identifiers

sp_acs

This is your Assertion Consumer Service (ACS) endpoint.

After authentication, the Identity Provider redirects the user back to this endpoint.

In our case:

/auth/saml2/callback

Enter fullscreen mode Exit fullscreen mode

sp_default_binding_method

This defines how SAML responses are transmitted.

Using POST binding is generally the safest and most common option.

Creating the Controller

A dedicated controller keeps the authentication flow clean and isolated.

<?php

namespace App\Http\Controllers\Auth;

use App\Services\SAML2Service;
use Filament\Notifications\Notification;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;

class SAML2Controller extends Controller
{
    public function __construct(protected SAML2Service $saml2Service) {}

    public function metadata(): Response
    {
        return $this->saml2Service->metadata();
    }

    public function redirect(): RedirectResponse
    {
        return $this->saml2Service->redirect();
    }

    public function callback(): RedirectResponse
    {
        $user = $this->saml2Service->callback();

        if (! $user) {
            Notification::make()
                ->title(__('Unable to connect. Please contact an administrator.'))
                ->danger()
                ->send();
        }

        return redirect(filament()->getUrl());
    }
}

Enter fullscreen mode Exit fullscreen mode

Why Use a Dedicated Service?

Many authentication tutorials place all the logic directly inside the controller.

This quickly becomes difficult to maintain when adding:

  • role synchronization
  • multiple providers
  • access policies
  • audit logging
  • tenant support

Moving the SAML logic into a dedicated service keeps the architecture maintainable.

Defining the Routes

Next, create the authentication web routes:

Route::prefix('auth/saml2')
    ->name('auth.saml2.')
    ->controller(\App\Http\Controllers\Auth\SAML2Controller::class)
    ->group(function () {
        Route::get('metadata', 'metadata')->name('metadata');
        Route::get('redirect', 'redirect')->name('login');
        Route::post('callback', 'callback')->name('callback');
    });

Enter fullscreen mode Exit fullscreen mode

This gives us:

  • /auth/saml2/metadata : Service Provider metadata
  • /auth/saml2/redirect : Redirect to Identity Provider
  • /auth/saml2/callback : Handle SAML response

Building the SAML Service

Now let’s implement the service.

<?php

namespace App\Services;

use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use SocialiteProviders\Saml2\Provider;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SAML2Service
{
    public function redirect(): RedirectResponse
    {
        return Socialite::driver('saml2')->redirect();
    }

    public function callback(): ?User
    {
        /** @var Provider $saml2Provider */
        $saml2Provider = Socialite::driver('saml2');

        /** @var \SocialiteProviders\Saml2\User $socialiteUser */
        $socialiteUser = $saml2Provider->stateless()->user();

        $user = User::query()->updateOrCreate(
            ['email' => strtolower($socialiteUser->getEmail())],
            ['name' => $socialiteUser->getName()]
        );

        if ($user->canAccessPanel(Filament::getCurrentOrDefaultPanel())) {
            Auth::login($user);

            return $user;
        }

        return null;
    }

    public function metadata(): Response
    {
        /** @var Provider $saml2Provider */
        $saml2Provider = Socialite::driver('saml2');

        return $saml2Provider->getServiceProviderMetadata();
    }
}

Enter fullscreen mode Exit fullscreen mode

Understanding the Authentication Flow

Redirecting the User

return Socialite::driver('saml2')->redirect();

Enter fullscreen mode Exit fullscreen mode

This sends the user to the Identity Provider login page.

Depending on the environment, users may already be authenticated through their corporate session.

Retrieving the Authenticated User

$socialiteUser = $saml2Provider->stateless()->user();

Enter fullscreen mode Exit fullscreen mode

The provider validates the SAML response and extracts the user information.

At this stage, you usually receive:

  • email
  • first name
  • last name
  • groups
  • claims

The exact payload depends on your Identity Provider configuration.

Creating or Updating the User

User::query()->updateOrCreate(...)

Enter fullscreen mode Exit fullscreen mode

This approach allows users to authenticate without pre-creating accounts manually.

It also keeps user information synchronized automatically.

Restricting Filament Access

$user->canAccessPanel(...)

Enter fullscreen mode Exit fullscreen mode

This is an important step.

Authenticating a user does not necessarily mean they should access your Filament panel.

By checking panel access explicitly, you keep your authorization layer consistent with the rest of your application.

Generating Service Provider Metadata

One of the most useful features of the provider is automatic metadata generation.

return $saml2Provider->getServiceProviderMetadata();

Enter fullscreen mode Exit fullscreen mode

This endpoint can be shared directly with your Identity Provider administrator.

It avoids:

  • manually crafting XML files
  • configuration mistakes
  • certificate inconsistencies

In many enterprise environments, this alone saves a significant amount of setup time.

Improving the Login Experience in Filament

You can now add a custom login button inside your Filament login page.

For example with a render hook:

FilamentView::registerRenderHook(
    PanelsRenderHook::AUTH_LOGIN_FORM_BEFORE,
    fn (): View => view('filament.components.saml-login-button')
);

Enter fullscreen mode Exit fullscreen mode

In provider file (like AppServiceProvider.php boot function)

<x-filament::button
    href="{{ route('auth.saml2.login') }}"
    tag="a"
    color="primary"
    class="w-full"
    icon="heroicon-o-arrow-right-circle"
    aria-label="Connect with your SSO account"
>
    {{ __('Connect with your SSO account') }}
</x-filament::button>

Enter fullscreen mode Exit fullscreen mode

In view file filament.components.saml-login-button.blade.php

This provides a much cleaner enterprise login experience.

Testing

For local development and testing, I personally use MockSAML:

This is also why the default metadata configuration points to port 4000:

'metadata' => env(
    'SAML2_METADATA_URL',
    'http://localhost:4000/api/saml/metadata'
),

Enter fullscreen mode Exit fullscreen mode

Using a lightweight mock Identity Provider makes it much easier to test:

  • SAML authentication flows
  • user provisioning

Without requiring access to a real enterprise Active Directory during development.

What About Active Directory Groups?

At this point, authentication works.

However, most enterprise applications also need:

  • role synchronization with Active Directory group mapping
  • dynamic authorization

This is where things become significantly more interesting.

In the premium article, we’ll implement:

  • automatic role synchronization
  • group parsing from SAML claims
  • Active Directory CN extraction
  • role mapping strategies
  • production-ready access control

SAML authentication is often perceived as complex, but Laravel Socialite combined with the SAML2 provider makes the integration surprisingly clean.

By isolating the authentication flow into a dedicated service and integrating directly with Filament, you can build enterprise-ready authentication while keeping your application maintainable.

The next step is implementing proper authorization and Active Directory role synchronization.

To receive more articles like this one, subscribe to Filament Mastery!