Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Sso Bundle Laravel Package

benji07/sso-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require benji07/sso-bundle
    

    Ensure your composer.json includes the package under require.

  2. Enable the Bundle: Add to config/bundles.php:

    Benji07\SsoBundle\Benji07SsoBundle::class => ['all' => true],
    
  3. Routing: Import the bundle’s routing in config/routes.yaml:

    Benji07SsoBundle:
        resource: "@Benji07SsoBundle/Resources/config/routing.yml"
    
  4. Basic Security Configuration: Update config/packages/security.yaml:

    firewalls:
        main:
            sso:
                check_path: /sso/login_check
    
  5. First Use Case: Configure a single SSO provider (e.g., Steam) in config/packages/benji07_sso.yaml:

    benji07_sso:
        user_manager: app.user_manager
        providers:
            steam:
                service: benji07.sso.provider.steam
                options:
                    apiKey: "%env(STEAM_API_KEY)%"
    
  6. Create a User Manager: Implement UserManagerInterface and register it as a service in config/services.yaml:

    services:
        App\UserManager:
            class: App\Service\UserManager
            arguments: ["@doctrine.orm.entity_manager"]
    
  7. Test the Flow: Access /sso/login/steam to trigger the SSO login. Verify the user is redirected and authenticated.


Implementation Patterns

Workflows

  1. Provider Integration:

    • Extend AbstractProvider for custom providers (e.g., Discord, GitHub).
    • Override getAuthUrl() and getUserInfo() methods to handle provider-specific logic.
    • Example:
      // src/Service/DiscordProvider.php
      class DiscordProvider extends AbstractProvider {
          public function getAuthUrl() {
              return "https://discord.com/api/oauth2/authorize?...";
          }
      }
      
  2. User Management:

    • Implement findUser() to locate existing users by provider data (e.g., Steam ID).
    • Implement createUser() to handle new registrations or redirect to a registration form.
    • Example:
      // src/Service/UserManager.php
      public function findUser($providerName, $userInfo) {
          return $this->em->getRepository(User::class)
              ->findOneBy(['steamId' => $userInfo['steamid']]);
      }
      
  3. Session Handling:

    • Use $request->getSession()->get('sso_user') to access provider data after authentication.
    • Clear the session after processing:
      $request->getSession()->remove('sso_user');
      
  4. Post-Authentication Logic:

    • Use event listeners (e.g., SSOAuthenticationSuccessEvent) to trigger actions after login.
    • Example listener:
      // src/EventListener/SSOListener.php
      public function onSSOAuthSuccess(SSOAuthenticationSuccessEvent $event) {
          $user = $event->getUser();
          // Log user activity, update last login, etc.
      }
      
      Register in config/services.yaml:
      services:
          App\EventListener\SSOListener:
              tags:
                  - { name: kernel.event_listener, event: sso.authentication.success, method: onSSOAuthSuccess }
      
  5. Multi-Provider Setup:

    • Configure multiple providers in benji07_sso.providers and expose them in the UI via links:
      {% for providerName, _ in app.container.get('benji07_sso.provider.manager').getProviders() %}
          <a href="{{ path('sso_login', {'provider': providerName}) }}">{{ providerName|capitalize }}</a>
      {% endfor %}
      

Integration Tips

  • Symfony Flex: Use symfony/flex to auto-configure the bundle if available.
  • Environment Variables: Store API keys in .env (e.g., STEAM_API_KEY=your_key).
  • Doctrine ORM: Leverage Doctrine for user persistence (e.g., add steamId to your User entity).
  • Twig Extensions: Create a custom Twig extension to check if a user is logged in via SSO:
    // src/Twig/SSOExtension.php
    public function isSSOAuthenticated(Request $request) {
        return $request->getSession()->has('_security_main');
    }
    

Gotchas and Tips

Pitfalls

  1. Provider Service Naming:

    • Ensure the service ID in benji07_sso.providers matches the registered service name (e.g., benji07.sso.provider.steam).
    • Fix: Verify with bin/console debug:container benji07.sso.provider.
  2. Session Expiry:

    • SSO tokens may expire. Implement token refresh logic in providers if needed.
    • Tip: Use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage for debugging session data.
  3. User Manager Not Found:

    • If user_manager is misconfigured, the bundle throws a RuntimeException.
    • Fix: Double-check the service ID in benji07_sso.user_manager matches your registered service.
  4. CSRF Protection:

    • The /sso/login_check endpoint is vulnerable to CSRF if not properly secured.
    • Fix: Add CSRF protection in Symfony’s security config:
      firewalls:
          main:
              sso:
                  check_path: /sso/login_check
              csrf_protection: true
      
  5. Provider-Specific Quirks:

    • Some providers (e.g., Steam) require specific scopes or redirect URIs.
    • Tip: Refer to the provider’s documentation for exact getAuthUrl() parameters.

Debugging

  1. Enable Debug Mode: Set APP_ENV=dev in .env to see detailed errors and logs.

  2. Log Provider Responses: Add logging in your provider’s getUserInfo() method:

    $this->logger->debug('Provider response:', ['data' => $response]);
    
  3. Check Events: Use the debug:event-dispatcher command to verify if events are fired:

    bin/console debug:event-dispatcher
    
  4. Session Dump: Dump session data after SSO login to verify provider data:

    dump($request->getSession()->all());
    

Extension Points

  1. Custom Providers:

    • Extend AbstractProvider and register the service with the benji07.sso.provider.{name} tag.
    • Example service definition:
      services:
          benji07.sso.provider.discord:
              class: App\Service\DiscordProvider
              tags: ['benji07.sso.provider']
      
  2. Custom User Entities:

    • Extend your User entity to include provider-specific fields (e.g., steamId, discordId).
    • Example:
      // src/Entity/User.php
      /**
       * @ORM\Column(type="string", nullable=true)
       */
      private $steamId;
      
  3. Post-Authentication Redirects:

    • Override the SSOAuthenticationSuccessHandler to customize redirects:
      // src/EventListener/CustomSSOHandler.php
      public function onSSOAuthSuccess(SSOAuthenticationSuccessEvent $event) {
          $event->setRedirectUrl('/dashboard');
      }
      
      Register as a listener (as shown in Implementation Patterns).
  4. Two-Factor Authentication (2FA):

    • Trigger 2FA after SSO login by extending the UserManager:
      public function createUser($providerName, $userInfo) {
          $user = new User();
          // ... set user data ...
          if (!$user->hasTwoFactorEnabled()) {
              return $this->redirectTo2FA($user);
          }
          return $user;
      }
      
  5. Provider-Specific Templates:

    • Override the default Twig templates (e.g., sso/login.html.twig) in templates/Benji07SsoBundle/ to customize the login UI.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle