DEV Community

Philip Perry
Philip Perry

Posted on

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

Top comments (1)

Collapse
 
aungmyatmoe profile image
Aung Myat Moe

This really help though. Thank in advance.