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 Fpbundle Laravel Package

belvg/sso-fpbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup Steps

  1. Install the Package

    composer require galillei/ssobundle
    
  2. Copy Configuration Files

    • src/config/sso_fp.yamlconfig/routes/sso_fp.yaml
    • src/config/knpu_oauth2_client.yamlconfig/packages/knpu_oauth2_client.yaml
    • Update security.yaml with the provided providers, firewalls, and access_control rules.
  3. Environment Variables Add to .env:

    OAUTH_FACTORY_PORTAL_ID=your_client_id
    OAUTH_FACTORY_PORTAL_SECRET=your_client_secret
    
  4. Register Services Update config/services.yaml with the provided FactoryOauth2ClientProvider and app.factory.provider aliases.

  5. Run Migrations (if applicable) Check for database migrations in src/Migrations/ and publish them if needed:

    php bin/console make:migration
    php bin/console doctrine:migrations:migrate
    
  6. First Use Case: OAuth Login

    • Add a login button/link to your template:
      <a href="{{ path('connect_factoryportal_start') }}">Login with Factory Portal</a>
      
    • Test the flow by visiting /connect/factoryportal.

Implementation Patterns

Common Workflows

1. OAuth Authentication Flow

  • Trigger Login: Redirect users to /connect/factoryportal (route: connect_factoryportal_start).
  • Callback Handling: The bundle automatically handles the OAuth callback at /connect/factoryportal/check.
  • User Creation/Update: The FactoryPortalUserProvider loads or creates a user based on the OAuth response.
    // Example: Manually trigger OAuth login in a controller
    use Symfony\Component\HttpFoundation\RedirectResponse;
    use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
    
    public function login(UrlGeneratorInterface $urlGenerator): RedirectResponse
    {
        return $this->redirect($urlGenerator->generate('connect_factoryportal_start'));
    }
    

2. Customizing User Data Mapping

Override the default user provider to map OAuth attributes to your User entity:

# config/services.yaml
SSO\FpBundle\Provider\FactoryPortalUserProvider:
    arguments:
        $userClass: App\Entity\CustomUser
        $attributeToPropertyMap:
            email: email
            first_name: firstName
            last_name: lastName
            # Add custom mappings as needed

3. Post-Authentication Logic

Extend the authenticator to run logic after successful login:

use SSO\FpBundle\Security\FactoryPortalAuthenticator;

class CustomFactoryPortalAuthenticator extends FactoryPortalAuthenticator
{
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        $user = $token->getUser();
        // Add custom logic (e.g., log activity, assign roles)
        return parent::onAuthenticationSuccess($request, $token, $firewallName);
    }
}

Update security.yaml to use your custom authenticator:

custom_authenticators:
    - App\Security\CustomFactoryPortalAuthenticator

4. Logout Handling

Redirect users to the Factory Portal logout endpoint:

<a href="{{ path('app_logout') }}">Logout</a>

The app_logout route triggers a logout from both your app and the Factory Portal (if configured).


Integration Tips

Leveraging KnpOAuth2ClientBundle

The bundle relies on knpuniversity/oauth2-client-bundle. Customize OAuth clients in config/packages/knpu_oauth2_client.yaml:

clients:
    factory_portal:
        type: oauth2
        client_id: '%env(OAUTH_FACTORY_PORTAL_ID)%'
        client_secret: '%env(OAUTH_FACTORY_PORTAL_SECRET)%'
        provider: factory_portal
        scopes: 'email profile'
        options:
            authorization_options:
                scope: { value: 'email profile' }

Role-Based Access Control

Use the IS_AUTHENTICATED_FULLY rule to protect routes after OAuth login. For granular control, extend the access_control section:

access_control:
    - { path: ^/dashboard, roles: ROLE_USER }
    - { path: ^/admin, roles: ROLE_ADMIN }

Testing the Flow

Use Symfony’s HATEAAS or manual testing to verify:

  • Redirect to /connect/factoryportal triggers OAuth flow.
  • Callback at /connect/factoryportal/check creates/updates a user.
  • Logout at /app_logout clears sessions.

Gotchas and Tips

Pitfalls

1. Missing Environment Variables

  • Issue: OAuth fails silently if OAUTH_FACTORY_PORTAL_ID or OAUTH_FACTORY_PORTAL_SECRET are missing.
  • Fix: Validate .env and restart the server:
    php bin/console cache:clear
    

2. User Provider Mismatch

  • Issue: If app_user_provider in security.yaml doesn’t match the bundle’s provider, authentication fails.
  • Fix: Ensure the provider ID is correct:
    providers:
        app_user_provider:
            id: SSO\FpBundle\Provider\FactoryPortalUserProvider
    

3. Route Conflicts

  • Issue: The bundle defines routes like connect_factoryportal_start. Conflicts may arise if you manually define similar routes.
  • Fix: Check config/routes/sso_fp.yaml and update routes.yaml:
    sso_fp:
        resource: "@SSOFpBundle/Resources/config/routes.yaml"
        prefix: /
    

4. CSRF Token Errors

  • Issue: POST requests to /connect/factoryportal/check may fail with CSRF errors.
  • Fix: Ensure the callback route is configured to accept CSRF tokens or disable CSRF for the route in security.yaml:
    firewalls:
        main:
            # ...
            form_login:
                csrf_token_generator: security.csrf.token_manager
    

Debugging Tips

1. Enable OAuth Debugging

Add this to config/packages/knpu_oauth2_client.yaml to log OAuth responses:

clients:
    factory_portal:
        # ...
        options:
            logging: true

2. Check User Provider Logs

Temporarily add logging to the user provider:

// In FactoryPortalUserProvider
public function loadUserByOAuthUserResponse(OAuthUser $response)
{
    $this->logger->debug('OAuth response:', ['response' => $response->toArray()]);
    // ...
}

3. Validate Token Storage

If users aren’t persisting, check:

  • The User entity has the correct properties (e.g., email, firstName).
  • Doctrine events (e.g., prePersist, preUpdate) aren’t modifying the user unexpectedly.

Extension Points

1. Custom OAuth Attributes

Extend the FactoryOauth2ClientProvider to fetch additional attributes:

use SSO\FpBundle\Provider\FactoryOauth2ClientProvider;

class CustomOauth2ClientProvider extends FactoryOauth2ClientProvider
{
    public function getAdditionalParameters(): array
    {
        return [
            'prompt' => 'consent',
            'additional_params' => ['custom_param' => 'value'],
        ];
    }
}

Register it in services.yaml:

SSO\FpBundle\Provider\FactoryOauth2ClientProvider:
    class: App\Provider\CustomOauth2ClientProvider

2. Post-Login Redirects

Customize the redirect after login in the authenticator:

public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
    $targetPath = $this->getTargetPath($request->getSession(), new UrlGeneratorInterface());
    return new RedirectResponse($targetPath ?: '/dashboard');
}

3. Multi-Provider Support

Reuse the bundle’s patterns to add support for other OAuth providers by:

  • Creating a new *Authenticator class.
  • Extending FactoryPortalUserProvider for provider-specific logic.
  • Adding new routes and firewall rules.

4. Event Listeners

Hook into the bundle’s events to run logic before/after authentication:

use SSO\FpBundle\Event\FactoryPortalAuthEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;

#[AsEventListener(event: 'factory_portal
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor