DEV Community

Philip Perry
Philip Perry

Posted on

5

Integrating SSO with Laravel Auth Provider

At my company we have our own SSO server (based on Laravel passport) and we use our sdk (Laravel package) that provides the middleware and other functionality to communicate with the SSO server and we add to all our microservices.

We decided to add the functionality of the SDK so that our SSO user data gets passed into the Auth provider. The Auth facade allows one to do things like fetching the logged-in user with Auth::user(). Thankfully Laravel allows one to extend the user provider

One of the methods that can be overwritten is retrieveById. Our code to fill the Auth user looks something like this (simplified):

<?php
namespace Company\SSO\Auth\UserProviders;

use Illuminate\Contracts\Auth\Authenticatable
use Illuminate\Contracts\Auth\UserProvider;

class SSOUserProvider implements UserProvider
{
  public function retrieveById($identifier): ?Authenticatable
  {
    $user = SSO::webUser(); //this fetches the web user from  our SSO server

   if(!$user) { 
    return null;
   }

  /**
  * LaravelUser is a class that we created that implements the
  * Authenticatable contract 
  */
  return new LaravelUser(
    $user->id,
    $user->name,
    $user->email,
    $user->emailVerifiedAt,
    $user->isAdmin,
    $user->createdAt,
    $user->updatedAt,
    $user->activeGroup 
  );
 }
}
Enter fullscreen mode Exit fullscreen mode

The custom user provider needs to be added to the auth.php config and resolved in the boot method of the ServiceProvider class. You can read about this here: Adding custom user providers

We actually went a step further and also added custom guards by using Auth::extend() in the boot method of the ServiceProvider. For that we pretty much followed what is described here: Adding custom guards

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
aungmyatmoe profile image
Aung Myat Moe

This really help though. Thank in advance.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay