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 Auth Bundle Laravel Package

damax/api-auth-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require damax/api-auth-bundle
    

    Add to config/bundles.php:

    Damax\ApiAuthBundle\DamaxApiAuthBundle::class => ['all' => true],
    
  2. Basic Configuration Publish the default config:

    php bin/console damax:api-auth:install
    

    Edit config/packages/damax_api_auth.yaml to define:

    • api_key (storage, extractors, TTL)
    • jwt (secret key, claims, refresh token settings)
  3. First Use Case: API Key Auth

    • Generate a key via CLI:
      php bin/console damax:api-auth:api-key:create --user-id=1 --name="Test Key"
      
    • Use in requests:
      GET /api/endpoint
      Authorization: Bearer <api-key>
      
    • Or via query param:
      GET /api/endpoint?api_key=<api-key>
      
  4. First Use Case: JWT Auth

    • Obtain a token via /api/login endpoint (if using Symfony’s security).
    • Use in requests:
      GET /api/protected
      Authorization: Bearer <jwt-token>
      

Implementation Patterns

API Key Workflows

  1. Key Storage

    • Database: Use api_key.storage.database with a custom ApiKey entity.
      # config/packages/damax_api_auth.yaml
      api_key:
          storage:
              database: true
      
    • Redis: Enable with api_key.storage.redis and configure host/port.
    • Config: Store keys directly in api_key.keys (for testing only).
  2. Key Extraction Chain Customize the order of extractors (cookie, header, query) in api_key.extractors:

    api_key:
        extractors:
            - header
            - query
            - cookie
    
  3. TTL Management Set default TTL for keys:

    api_key:
        ttl: 3600  # 1 hour in seconds
    

    Override per-key via CLI:

    php bin/console damax:api-auth:api-key:create --user-id=1 --ttl=86400
    
  4. Custom User Provider Extend ApiKeyUserProvider to fetch users from non-standard sources (e.g., LDAP):

    // src/Security/ApiKey/CustomApiKeyUserProvider.php
    class CustomApiKeyUserProvider extends ApiKeyUserProvider
    {
        protected function loadUserByApiKey($apiKey)
        {
            // Custom logic here
        }
    }
    

    Register in services.yaml:

    services:
        Damax\ApiAuthBundle\Security\ApiKey\ApiKeyUserProvider:
            alias: App\Security\ApiKey\CustomApiKeyUserProvider
    

JWT Workflows

  1. Token Generation Use Symfony’s authentication_utils or a custom controller:

    use Damax\ApiAuthBundle\Security\Authenticator\JwtAuthenticator;
    
    // In a controller
    $token = $this->get('lexik_jwt_authentication.jwt_manager')->create($payload);
    
  2. Custom Claims Add claims to the JWT payload:

    # config/packages/damax_api_auth.yaml
    jwt:
        claims:
            custom:
                role: ROLE_API_USER
                scope: ['read', 'write']
    
  3. Refresh Tokens Enable refresh token support:

    jwt:
        refresh_token:
            enabled: true
            ttl: 86400  # 24 hours
    

    Implement a /refresh endpoint to handle token rotation.

  4. Response Customization Override default success/error responses by extending the JwtAuthenticator:

    // src/Security/Authenticator/CustomJwtAuthenticator.php
    class CustomJwtAuthenticator extends JwtAuthenticator
    {
        public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName)
        {
            return new JsonResponse(['token' => $token->getCredentials()]);
        }
    }
    

Integration with Symfony Security

  1. Firewall Configuration Add to security.yaml:

    firewalls:
        api:
            pattern: ^/api
            stateless: true
            json_login:
                check_path: /api/login
                username_path: username
                password_path: password
            jwt: ~
            api_key: ~
    
  2. Role-Based Access Use Symfony’s voter system or custom logic to restrict endpoints:

    // src/Security/Voter/ApiKeyVoter.php
    class ApiKeyVoter extends Voter
    {
        protected function supports(string $attribute, mixed $subject): bool
        {
            return $attribute === 'ROLE_API_KEY';
        }
    
        protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
        {
            // Custom logic
        }
    }
    

Gotchas and Tips

API Key Pitfalls

  1. Extractor Order Matters

    • If api_key is passed in both header and query, the first extractor in the chain wins.
    • Debug with:
      php bin/console debug:config damax_api_auth
      
  2. Case Sensitivity

    • API keys are case-sensitive by default. Normalize in ApiKeyUserProvider if needed:
      $apiKey = strtolower($apiKey);
      
  3. TTL Edge Cases

    • Keys with ttl: 0 are permanent. Set to null to disable TTL entirely.
    • Redis TTL is in seconds; ensure your config matches.
  4. Concurrent Requests

    • Redis storage handles concurrent requests better than database. Use Redis for high-traffic APIs.
  5. Key Revocation

    • No built-in revocation system. Implement a revoked_keys Redis set or database flag:
      php bin/console damax:api-auth:api-key:revoke --key=<key-id>
      

JWT Quirks

  1. Symmetric vs. Asymmetric

    • Symmetric (default) is faster but less secure. Use asymmetric (RSA) for production:
      jwt:
          secret_key: "%kernel.project_dir%/config/jwt/private.pem"
          public_key:  "%kernel.project_dir%/config/jwt/public.pem"
      
  2. Token Size Limits

    • Large payloads may exceed HTTP header limits (~8KB). Compress or split into multiple tokens.
  3. Clock Skew

    • JWTs use nbf (not before) and exp (expiry) claims. Ensure server time is synchronized:
      jwt:
          leeway: 30  # Allow 30-second clock skew
      
  4. Refresh Token Security

    • Store refresh tokens in HTTP-only cookies or secure headers to prevent XSS.
    • Implement single-use refresh tokens to mitigate token leakage.
  5. Custom Claims Serialization

    • Non-standard claims must implement JsonSerializable or be JSON-serializable:
      $payload['custom_claim'] = new class implements JsonSerializable {
          public function jsonSerialize() { return ['data' => 'value']; }
      };
      

Debugging Tips

  1. Enable Verbose Logging

    # config/packages/monolog.yaml
    handlers:
        api_auth:
            type: stream
            path: "%kernel.logs_dir%/api_auth.log"
            level: debug
    
  2. CLI Commands

    • List all keys:
      php bin/console damax:api-auth:api-key:list
      
    • Lookup a key:
      php bin/console damax:api-auth:api-key:lookup --key=<key>
      
  3. Event Listeners

    • Subscribe to api_key.authenticated and jwt.authenticated events for custom logic:
      // src/EventListener/AuthListener.php
      class AuthListener
      {
          public function onApiKeyAuthenticated(ApiKeyAuthenticatedEvent $event)
          {
              // Log or modify user data
          }
      }
      
  4. Testing

    • Use ApiKeyFactory in PHPUnit:
      $apiKey = $this->get('damax_api_auth.api_key.factory')->create('user1', ['role' => 'ROLE_TEST']);
      
    • Mock the JwtManager for JWT tests:
      $this->mock(JwtManager::class)->shouldReceive('create')->once();
      

Extension Points

  1. Custom Storage Implement ApiKeyStorageInterface for non-Redis
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