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

Eu Login Api Authentication Bundle Laravel Package

ecphp/eu-login-api-authentication-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

This package, EU Login API Authentication Bundle, integrates with the EU Login API to authenticate users via European Union identity providers (e.g., eIDAS). To get started:

  1. Installation:

    composer require ecphp/eu-login-api-authentication-bundle
    

    Ensure your project meets the updated requirements:

    • PHP 8.1+ (default in this release).
    • Symfony 6.4+ or 7.0+ (Symfony 7 compatibility added in 1.0.6).
    • Laravel users: Use the Symfony bridge (e.g., symfony/http-foundation) or wrap the bundle in a Laravel-specific adapter.
  2. Configuration: Publish the bundle’s config:

    php artisan vendor:publish --provider="ECPHP\EuLoginApiAuthenticationBundle\EuLoginApiAuthenticationBundle"
    

    Update .env with your EU Login API credentials (e.g., EU_LOGIN_CLIENT_ID, EU_LOGIN_SECRET).

  3. First Use Case: Add the authentication route to your routes/web.php or routes/api.php:

    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\Routing\Annotation\Route;
    
    class EuLoginController extends AbstractController
    {
        #[Route('/login/eu', name: 'eu_login')]
        public function redirectToEuLogin(): Response
        {
            return $this->redirect($this->get('eu_login.api_authenticator')->getLoginUrl());
        }
    }
    

    Test the flow by visiting /login/eu and verifying the redirect to the EU Login provider.


Implementation Patterns

Core Workflows

  1. Authentication Flow:

    • Use the EuLoginApiAuthenticator service to generate login URLs and handle callbacks:
      $loginUrl = $this->get('eu_login.api_authenticator')->getLoginUrl(['redirect_uri' => route('eu_login.callback')]);
      
    • Process the callback in a controller:
      #[Route('/login/eu/callback', name: 'eu_login.callback')]
      public function handleEuLoginCallback(Request $request)
      {
          $user = $this->get('eu_login.api_authenticator')->authenticate($request);
          // Store user data (e.g., in session or database).
          return $this->redirectToRoute('home');
      }
      
  2. User Data Handling:

    • Fetch user attributes post-authentication:
      $userInfo = $this->get('eu_login.api_authenticator')->getUserInfo($user);
      // Example: $userInfo['given_name'], $userInfo['email']
      
  3. Session Integration:

    • Bind the authenticated user to Symfony’s security component (if using Symfony) or Laravel’s auth system:
      $this->get('security.token_storage')->setToken(
          new UsernamePasswordToken($request->getSession(), $user->getEmail(), $user->getRoles())
      );
      

Integration Tips

  • Laravel-Specific:

    • For Laravel, create a facade or service wrapper to interact with the bundle’s Symfony services:
      namespace App\Services;
      
      use Illuminate\Support\Facades\Facade;
      
      class EuLoginService extends Facade
      {
          protected static function getFacadeAccessor() { return 'eu_login.api_authenticator'; }
      }
      
    • Use Laravel’s Auth facade to handle user sessions:
      Auth::loginUsingId($user->getId());
      
  • Custom Providers:

    • Extend the bundle’s EuLoginApiAuthenticator to support additional EU member state providers or custom scopes:
      class CustomEuLoginAuthenticator extends EuLoginApiAuthenticator
      {
          protected function getProviderConfig(): array
          {
              return array_merge(parent::getProviderConfig(), [
                  'scopes' => ['openid', 'profile', 'email', 'custom_scope'],
              ]);
          }
      }
      
    • Register the custom service in config/services.php:
      'eu_login.api_authenticator' => App\Services\CustomEuLoginAuthenticator::class,
      
  • Testing:

    • Use the bundle’s built-in test utilities (updated in 1.0.6) to mock the EU Login API:
      $this->get('eu_login.api_authenticator')->shouldReceive('fetchUserInfo')
          ->once()
          ->andReturn(['given_name' => 'Test', 'email' => 'test@example.com']);
      

Gotchas and Tips

Breaking Changes in 1.0.6

  1. Symfony 7 Compatibility:

    • The bundle now requires Symfony 7.0+ (or 6.4+ with updated dependencies). If you’re on Symfony 6.3 or lower, pin to 1.0.5 or upgrade Symfony first.
    • Migration Tip: Update composer.json to require ^7.0 for Symfony bundles and run:
      composer update symfony/* --with-all-dependencies
      
  2. PHP Version:

    • Default PHP version is now 8.1+. Ensure your environment matches:
      php -v  # Should show 8.1.x or 8.2.x
      
  3. Deprecations:

    • The refactor: fix deprecation commit (cc4ebf7) and its revert (a02cf42) suggest internal API changes. Avoid relying on undocumented methods in the bundle’s core classes.

Debugging Tips

  1. Callback Errors:

    • If the /login/eu/callback route fails, verify:
      • The state parameter matches the session (enable EU_LOGIN_DEBUG=true in .env to log states).
      • The redirect_uri in the initial request matches the callback URL exactly (including http vs. https).
  2. User Info Missing:

    • Ensure the EU Login provider returns the expected scopes (e.g., profile, email). Add these to your provider config:
      # config/packages/eu_login_api_authentication.yaml
      eu_login_api_authentication:
          scopes: ['openid', 'profile', 'email']
      
  3. Static Analysis Warnings:

    • The psalm fixes in 1.0.6 may reveal type-related issues. Run:
      vendor/bin/psalm --init
      vendor/bin/psalm
      
    • Suppress false positives in psalm.xml if needed.

Extension Points

  1. Custom User Entity:

    • Map EU Login attributes to your user model by extending the EuLoginUserProvider:
      class CustomUserProvider extends EuLoginUserProvider
      {
          public function loadUserByToken(string $token): UserInterface
          {
              $userData = parent::loadUserByToken($token);
              return new App\Entity\User([
                  'name' => $userData['given_name'],
                  'email' => $userData['email'],
                  // Add custom fields.
              ]);
          }
      }
      
    • Register the provider in config/packages/security.yaml:
      providers:
          eu_login:
              id: App\Security\CustomUserProvider
      
  2. API Rate Limiting:

    • The bundle uses Guzzle for HTTP requests. Add middleware to handle rate limits:
      $client = new Client([
          'middleware' => [
              new RetryMiddleware([
                  'max_retries' => 3,
                  'delay' => 100,
              ]),
          ],
      ]);
      
    • Inject the custom client into the authenticator via dependency injection.
  3. Logging:

    • Enable verbose logging in .env:
      EU_LOGIN_DEBUG=true
      EU_LOGIN_LOG_LEVEL=debug
      
    • Monitor logs in var/log/dev.log (Symfony) or Laravel’s storage/logs.
  4. CI/CD Updates:

    • The bundle dropped scrutinizer in favor of readthedocs.yml. Update your CI config to avoid failures:
      # .github/workflows/test.yml
      jobs:
        test:
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - run: composer install
            - run: php vendor/bin/phpunit
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware