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

Oauth2 Uco Bundle Laravel Package

aulasoftwarelibre/oauth2-uco-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require aulasoftwarelibre/oauth2-uco-bundle
    

    Enable in config/bundles.php:

    Aulasoftwarelibre\OAuth2UcoBundle\OAuth2UcoBundle::class => ['all' => true],
    
  2. Configure the Bundle Add to config/packages/security.yaml:

    security:
        providers:
            uco_provider:
                id: aulasoftwarelibre.oauth2_uco.user_provider
        firewalls:
            main:
                oauth:
                    resource_owners:
                        uco:
                            label: "University of Córdoba"
                            provider: aulasoftwarelibre.oauth2_uco
                            client_id: "%env(UCO_CLIENT_ID)%"
                            client_secret: "%env(UCO_CLIENT_SECRET)%"
                            scope: "openid profile email"
    
  3. Environment Variables Add to .env:

    UCO_CLIENT_ID=your_client_id
    UCO_CLIENT_SECRET=your_client_secret
    UCO_REDIRECT_URI=http://your-app.com/connect/uco/check
    
  4. First Use Case: Login Button Add a login link in your template:

    <a href="{{ path('connect_uco_check') }}">Login with University of Córdoba</a>
    

Implementation Patterns

Workflow: OAuth2 Flow Integration

  1. Authentication Route The bundle auto-generates routes (connect_uco_check, connect_uco_login, etc.). Use connect_uco_check to initiate the OAuth2 flow.

  2. User Provider Extend the default user provider to map UCO attributes to your user entity:

    // src/Service/UserProvider.php
    use Aulasoftwarelibre\OAuth2UcoBundle\Security\User\UcoUserProvider;
    
    class CustomUcoUserProvider extends UcoUserProvider
    {
        public function loadUserByUsername($username)
        {
            // Custom logic to fetch user from DB
        }
    
        public function loadUserByOAuthUserResponse(OAuthUserResponse $response)
        {
            $email = $response->getEmail();
            $firstName = $response->getFirstName();
            // Map UCO data to your user entity
        }
    }
    
  3. Post-Authentication Logic Use Symfony’s AUTHENTICATION_SUCCESS event to handle post-login actions:

    // src/EventListener/AuthListener.php
    use Symfony\Component\Security\Http\Event\AuthenticationSuccessEvent;
    
    class AuthListener
    {
        public function onAuthenticationSuccess(AuthenticationSuccessEvent $event)
        {
            $user = $event->getUser();
            // Log, redirect, or update user metadata
        }
    }
    
  4. Messenger Integration Dispatch messages after authentication:

    use Symfony\Component\Messenger\MessageBusInterface;
    
    class AuthListener
    {
        public function __construct(private MessageBusInterface $bus)
        {}
    
        public function onAuthenticationSuccess(AuthenticationSuccessEvent $event)
        {
            $this->bus->dispatch(new UserLoggedInEvent($event->getUser()));
        }
    }
    

Integration Tips

  • Doctrine Integration Use symfony/doctrine-bridge to persist user data:

    // In loadUserByOAuthUserResponse
    $entityManager = $this->getEntityManager();
    $user = new YourUserEntity();
    $user->setEmail($response->getEmail());
    $entityManager->persist($user);
    $entityManager->flush();
    
  • Custom Claims Mapping Override UcoUserProvider to map custom claims from the UCO response:

    public function loadUserByOAuthUserResponse(OAuthUserResponse $response)
    {
        $claims = $response->getClaims();
        $userData = [
            'email' => $claims['email'] ?? null,
            'name' => $claims['name'] ?? null,
            'uco_id' => $claims['sub'] ?? null, // UCO-specific identifier
        ];
        // Proceed with user creation/loading
    }
    
  • Logout Handling Redirect users to UCO’s logout endpoint:

    <a href="{{ path('logout') }}?logout=uco">Logout</a>
    

    Configure in security.yaml:

    firewalls:
        main:
            logout:
                path: logout
                target: uco_logout
    

Gotchas and Tips

Pitfalls

  1. Missing Redirect URI Ensure UCO_REDIRECT_URI matches exactly what’s registered in the UCO OP dashboard. Mismatches cause invalid_redirect_uri errors.

  2. Scope Mismatch The UCO OP may reject requests if scopes aren’t whitelisted. Stick to openid profile email unless documented otherwise.

  3. User Provider Not Registered Forgetting to configure the uco_provider in security.yaml under providers will break authentication.

  4. AGPL License Compliance The bundle is AGPL-3.0. Ensure your project complies with the license if distributing closed-source software.


Debugging

  1. Enable OAuth2 Debugging Add to config/packages/dev/oauth.yaml:

    oauth:
        clients:
            uco:
                debug: true
    
  2. Check UCO Response Dump the OAuth response in loadUserByOAuthUserResponse:

    dump($response->getClaims());
    
  3. Symfony Debug Toolbar Use the Security panel to inspect the authenticated user and provider.


Extension Points

  1. Custom User Entity Override UcoUserProvider to support non-standard user entities:

    class CustomUcoUserProvider extends UcoUserProvider
    {
        public function __construct(private EntityManagerInterface $em, private string $userClass)
        {
            $this->userClass = $userClass;
        }
    }
    
  2. Additional Claims Extend the bundle’s UcoUser class to include custom attributes:

    // src/Entity/CustomUser.php
    use Aulasoftwarelibre\OAuth2UcoBundle\Security\User\UcoUser;
    
    class CustomUser extends UcoUser
    {
        private ?string $ucoDepartment;
    
        public function setUcoDepartment(?string $department): self
        {
            $this->ucoDepartment = $department;
            return $this;
        }
    }
    
  3. Messenger Middleware Add middleware to validate UCO tokens before processing messages:

    // config/packages/messenger.yaml
    framework:
        messenger:
            transports:
                async: '%env(MESSENGER_TRANSPORT_DSN)%'
            routing:
                'App\Message\UcoEvent': async
            failure_transport: failed
            transports:
                uco_validator:
                    dsn: 'doctrine://default'
                    middleware:
                        - 'App\Middleware\ValidateUcoTokenMiddleware'
    

Configuration Quirks

  1. Doctrine Cache If using Doctrine, ensure the cache is configured to avoid ClassNotFoundException:

    # config/packages/doctrine.yaml
    doctrine:
        orm:
            metadata_cache_driver: apcu
            query_cache_driver: apcu
            result_cache_driver: apcu
    
  2. Environment Overrides Override bundle config via config/packages/aulasoftwarelibre_oauth2_uco.yaml:

    aulasoftwarelibre_oauth2_uco:
        client_id: "%env(UCO_CLIENT_ID)%"
        client_secret: "%env(UCO_CLIENT_SECRET)%"
        scope: ["openid", "profile", "email", "custom_scope"]
    
  3. CSRF Protection Disable CSRF for OAuth2 endpoints if needed (not recommended for production):

    # config/packages/security.yaml
    firewalls:
        main:
            pattern: ^/connect/uco
            security: false
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui