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

Api Gw Authentication Bundle Laravel Package

ecphp/api-gw-authentication-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ecphp/api-gw-authentication-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Ecphp\ApiGatewayAuthenticationBundle\EcphpApiGatewayAuthenticationBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console config:dump-reference EcphpApiGatewayAuthenticationBundle
    

    Update config/packages/ecphp_api_gw_authentication.yaml with your API Gateway credentials (client ID, secret, and endpoint).

  3. First Use Case Protect a route with the api_gateway_auth firewall:

    # config/packages/security.yaml
    firewalls:
        api:
            pattern: ^/api
            stateless: true
            provider: api_gateway_auth
            guard:
                authenticators:
                    - Ecphp\ApiGatewayAuthenticationBundle\Security\ApiGatewayAuthenticator
    

Implementation Patterns

Authentication Workflow

  1. Request Flow

    • The bundle intercepts requests via the ApiGatewayAuthenticator.
    • Validates the Authorization header (format: Bearer <token>).
    • Exchanges the token with the API Gateway for a user identity (e.g., ECAS or corporate service user).
  2. User Provider Integration

    • Extend Ecphp\ApiGatewayAuthenticationBundle\Security\User\ApiGatewayUserProvider to map API Gateway responses to Laravel/Symfony users:
      class CustomUserProvider extends ApiGatewayUserProvider
      {
          public function loadUserByIdentifier($identifier): UserInterface
          {
              // Fetch user from your DB or external service
              return new User($identifier, $this->getPasswordEncoder());
          }
      }
      
    • Register the provider in security.yaml:
      providers:
          api_gateway_auth:
              id: Ecphp\ApiGatewayAuthenticationBundle\Security\User\CustomUserProvider
      
  3. Token Refresh

    • Use the ApiGatewayTokenManager to refresh tokens:
      $tokenManager = $container->get('ecphp_api_gw_auth.token_manager');
      $refreshedToken = $tokenManager->refreshToken($expiredToken);
      

Common Use Cases

  • API Gateway Proxy: Use the bundle to validate tokens for requests forwarded from the EC’s API Gateway.
  • Hybrid Auth: Combine with other authenticators (e.g., JWT) for multi-provider APIs.
  • Role-Based Access: Attach roles to users post-authentication via the loadUserByIdentifier method.

Gotchas and Tips

Pitfalls

  1. Token Validation Failures

    • Issue: Silent failures if the API Gateway endpoint is unreachable.
    • Fix: Enable debug mode and check logs for Ecphp\ApiGatewayAuthenticationBundle\Exception\TokenValidationException.
    • Workaround: Implement a fallback mechanism (e.g., cache valid tokens temporarily).
  2. Header Mismatches

    • Issue: The bundle expects the Authorization header in the format Bearer <token>. Misconfigured proxies or load balancers may strip/modify headers.
    • Fix: Verify headers at the edge (e.g., Nginx/Apache) or use middleware to reattach them:
      $request->headers->set('Authorization', $request->server->get('HTTP_AUTHORIZATION'));
      
  3. User Provider Gaps

    • Issue: If loadUserByIdentifier returns null, the authenticator fails silently.
    • Fix: Throw UserNotFoundException or log a warning:
      if (null === $user) {
          throw new UserNotFoundException('User not found for identifier: '.$identifier);
      }
      

Debugging Tips

  • Enable Verbose Logging Add to config/packages/monolog.yaml:

    handlers:
        api_gw:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.api_gw.log"
            level: debug
            channels: ["api_gateway_auth"]
    
  • Test Locally Use a mock API Gateway endpoint (e.g., Mockoon) to simulate responses during development.

Extension Points

  1. Custom Token Validation Override Ecphp\ApiGatewayAuthenticationBundle\Security\ApiGatewayAuthenticator to add logic:

    protected function validateToken($token): bool
    {
        // Custom validation (e.g., check token issuer)
        return parent::validateToken($token) && $this->isIssuerValid($token);
    }
    
  2. Event Listeners Listen for api_gateway.auth.success and api_gateway.auth.failure events to log or modify responses:

    // src/EventListener/AuthListener.php
    public function onAuthSuccess(AuthSuccessEvent $event)
    {
        // Log or audit the authenticated user
    }
    

    Register in services.yaml:

    services:
        App\EventListener\AuthListener:
            tags:
                - { name: kernel.event_listener, event: api_gateway.auth.success, method: onAuthSuccess }
    
  3. Configuration Overrides Dynamically override settings (e.g., token TTL) via environment variables:

    # config/packages/ecphp_api_gw_authentication.yaml
    ecphp_api_gw_authentication:
        token_ttl: '%env(int:API_GW_TOKEN_TTL)%'
    
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