Weave 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

Authentication Bundle Laravel Package

atom/authentication-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require atom/authentication-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Atom\AuthenticationBundle\AtomAuthenticationBundle::class => ['all' => true],
    ];
    
  2. Configuration Add the bundle’s config to config/packages/atom_authentication.yaml:

    atom_authentication:
        secret_key: '%env(APP_SECRET_KEY)%'  # Must be a strong, unique key
        header_name: 'X-Auth-Token'         # Default HMAC header name
        algorithm: 'sha256'                 # Default HMAC algorithm
    
  3. First Use Case: Validating a Request Use the AtomAuthenticationListener to validate incoming API requests:

    use Atom\AuthenticationBundle\EventListener\AuthenticationListener;
    
    // In a controller or service:
    $token = $request->headers->get('X-Auth-Token');
    $isValid = $this->authenticationListener->validateToken($request, $token);
    

Implementation Patterns

Workflow: API Authentication Flow

  1. Client-Side Token Generation Clients generate an HMAC token using their secret key and request data:

    const crypto = require('crypto');
    const hmac = crypto.createHmac('sha256', 'client_secret_key');
    const signature = hmac.update(JSON.stringify(requestData)).digest('hex');
    
  2. Server-Side Validation In Symfony, use the AuthenticationListener to validate the token:

    // In a controller or event subscriber:
    public function onKernelRequest(GetResponseEvent $event) {
        $request = $event->getRequest();
        $token = $request->headers->get('X-Auth-Token');
    
        if (!$this->authenticationListener->validateToken($request, $token)) {
            throw new \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException('Invalid token');
        }
    }
    
  3. Integration with Security Component Extend Symfony’s security system by creating a custom Authenticator:

    use Atom\AuthenticationBundle\Security\Token\HMACUserToken;
    use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
    
    class HMACAuthenticator extends AbstractAuthenticator {
        public function supports(Request $request) {
            return $request->headers->has('X-Auth-Token');
        }
    
        public function authenticate(Request $request): TokenInterface {
            $token = $request->headers->get('X-Auth-Token');
            if (!$this->authenticationListener->validateToken($request, $token)) {
                throw new BadCredentialsException();
            }
            return new HMACUserToken('anon.', []);
        }
    }
    

Common Use Cases

  • API Gateway Validation: Validate tokens at the entry point of a microservice architecture.
  • Webhook Verification: Ensure incoming webhooks are from trusted sources.
  • Legacy System Integration: Secure API endpoints for older systems without OAuth2.

Gotchas and Tips

Pitfalls

  1. Secret Key Management

    • Issue: Hardcoding secret_key in config exposes it in logs or version control.
    • Fix: Use environment variables (%env(APP_SECRET_KEY)%) and restrict file permissions.
    • Tip: Rotate keys periodically and invalidate old tokens gracefully.
  2. Algorithm Mismatch

    • Issue: Client and server using different HMAC algorithms (e.g., sha1 vs. sha256).
    • Fix: Enforce a single algorithm in config and document it for clients.
  3. Token Replay Attacks

    • Issue: Stateless HMAC tokens are vulnerable to replay attacks.
    • Fix: Include a timestamp in the token payload and reject tokens outside a time window:
      $requestData = json_decode($request->getContent(), true);
      $currentTime = time();
      if (abs($requestData['timestamp'] - $currentTime) > 300) { // 5-minute window
          throw new \RuntimeException('Token expired');
      }
      
  4. Header Injection

    • Issue: Malicious users may inject headers to bypass validation.
    • Fix: Whitelist allowed headers in Symfony’s trusted_proxies or use a dedicated route prefix (e.g., /api/v1).

Debugging

  • Enable Verbose Logging Configure Monolog to log HMAC validation attempts:

    # config/packages/monolog.yaml
    handlers:
        main:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.log"
            level: debug
            channels: ["!event"]
    

    Then log validation results in the AuthenticationListener:

    $this->logger->debug('HMAC validation', ['valid' => $isValid, 'token' => $token]);
    
  • Test with curl Simulate client requests to verify token generation/validation:

    curl -X POST http://api.example.com/endpoint \
         -H "X-Auth-Token: $(echo -n 'data' | openssl dgst -sha256 -hmac 'client_secret')"
    

Extension Points

  1. Custom Token Payload Extend the AuthenticationListener to validate additional payload fields:

    public function validateToken(Request $request, string $token): bool {
        $requestData = json_decode($request->getContent(), true);
        return $this->validateHMAC($token, $requestData)
            && $this->validateCustomRules($requestData);
    }
    
    private function validateCustomRules(array $data): bool {
        return $data['user_id'] === 'expected_value';
    }
    
  2. Dynamic Secret Keys Fetch secrets from a database or cache for per-user keys:

    $userSecret = $this->secretService->getUserSecret($userId);
    return $this->validateHMAC($token, $requestData, $userSecret);
    
  3. Event-Based Extensions Dispatch events for pre/post-validation logic:

    // In AuthenticationListener
    $event = new PreAuthEvent($request, $token);
    $this->dispatcher->dispatch($event, PreAuthEvent::NAME);
    
    if ($event->isTokenRejected()) {
        return 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.
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge