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

Firebase Authentication Bundle Laravel Package

danieleambrosino/firebase-authentication-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require danieleambrosino/firebase-authentication-bundle
    

    Ensure FIREBASE_PROJECT_ID is set in .env:

    FIREBASE_PROJECT_ID=your-project-id
    
  2. Enable in Security Add to config/packages/security.yaml:

    security:
        firewalls:
            api:
                stateless: true
                firebase: ~
    
  3. First Use Case

    • Bearer Token Auth: Send a Firebase ID token in the Authorization: Bearer <token> header.
    • Cookie Auth: Ensure Firebase session cookies are set (e.g., via Firebase Auth client SDK).

    Test with:

    curl -H "Authorization: Bearer YOUR_FIREBASE_ID_TOKEN" http://your-app/api/protected-route
    

Key Files to Review

  • config/packages/firebase_authentication.yaml (default config)
  • src/FirebaseAuthenticator.php (core logic)
  • src/TokenResolver.php (token extraction)

Implementation Patterns

Workflows

  1. Bearer Token Authentication

    • Frontend: Use Firebase Auth client SDK to generate an ID token.
    • Backend: Validate token via Authorization header.
    • Example:
      // In a controller
      public function protectedRoute(): JsonResponse
      {
          $user = $this->getUser(); // User entity from Firebase
          return new JsonResponse(['user' => $user->getEmail()]);
      }
      
  2. Cookie-Based Authentication

    • Frontend: Set Firebase session cookies (e.g., firebaseauth).
    • Backend: Configure strategy: cookie in firewall and ensure same-site cookie policies are met.
    • Example Config:
      firewalls:
          main:
              firebase:
                  strategy: cookie
      
  3. Custom User Provider

    • Extend FirebaseUserProvider to map Firebase claims to your user model:
      use DanieleAmbrosino\FirebaseAuthenticationBundle\Security\User\FirebaseUserProvider;
      
      class CustomUserProvider extends FirebaseUserProvider
      {
          public function loadUserByUsername($username): UserInterface
          {
              $firebaseUser = parent::loadUserByUsername($username);
              return new YourUserEntity($firebaseUser->getEmail());
          }
      }
      
    • Register in security.yaml:
      providers:
          firebase:
              id: App\Security\CustomUserProvider
      
  4. Token Refresh Handling

    • Use Firebase’s ID token refresh logic on the frontend.
    • Backend: Validate tokens with exp claim (default TTL: 1 hour).

Integration Tips

  • API Platform: Combine with @Security("is_granted('ROLE_USER')") for automatic auth.
  • React/Vue: Use firebase/app and firebase/auth to handle token generation/refresh.
  • Testing: Mock Firebase tokens with:
    $token = $this->createMock(FirebaseToken::class);
    $token->method('getClaims')->willReturn(['uid' => 'test-user']);
    $this->container->set('firebase_auth.token_resolver', $token);
    

Gotchas and Tips

Pitfalls

  1. Token Validation Failures

    • Symptom: 401 Unauthorized with no debug info.
    • Fix: Enable debug mode in config/packages/firebase_authentication.yaml:
      debug: true
      
    • Check for:
      • Invalid FIREBASE_PROJECT_ID (verify in Firebase Console).
      • Malformed tokens (use Firebase DebugView).
      • Missing Authorization header or incorrect format.
  2. Cookie Strategy Quirks

    • SameSite Policy: Ensure cookies are SameSite=Lax or None (with Secure flag).
    • Domain Mismatch: Cookies must match the domain configured in Firebase Console.
    • CSRF: If using cookies, add csrf_token to protected routes.
  3. Time Skew Issues

    • Firebase tokens include an iat (issued at) and exp (expiry) timestamp.
    • Fix: Sync server time with NTP or adjust clock_skew in config:
      clock_skew: 60 # Allow 60-second skew
      
  4. Custom Claims Not Persisted

    • Firebase custom claims are not automatically synced to the backend.
    • Workaround: Use Firebase Admin SDK to fetch claims:
      use Firebase\Admin\Auth;
      
      $claims = Auth::getInstance()->getUser($uid)->getCustomClaims();
      

Debugging Tips

  • Log Tokens: Temporarily log tokens for inspection:
    $event = new FirebaseAuthEvent($token);
    $this->container->get('event_dispatcher')->dispatch($event, 'firebase_auth.token_validated');
    
  • Validate Manually: Use Firebase Admin SDK to verify tokens:
    use Firebase\Admin\Auth;
    
    try {
        $decoded = Auth::decodeIdToken($token);
    } catch (\Exception $e) {
        // Handle error
    }
    
  • Environment Variables: Double-check .env for:
    FIREBASE_PROJECT_ID=your-project-id
    FIREBASE_PRIVATE_KEY=... # Only needed if using Firebase Admin SDK
    

Extension Points

  1. Custom Token Resolver

    • Override TokenResolverInterface to extract tokens from custom headers:
      class CustomTokenResolver implements TokenResolverInterface
      {
          public function resolveToken(Request $request): ?string
          {
              return $request->headers->get('X-Custom-Token');
          }
      }
      
    • Register as a service:
      services:
          App\Security\CustomTokenResolver:
              tags: ['firebase_auth.token_resolver']
      
  2. Event Listeners

    • Listen for firebase_auth.token_validated to modify user data:
      use DanieleAmbrosino\FirebaseAuthenticationBundle\Event\FirebaseAuthEvent;
      
      public function onTokenValidated(FirebaseAuthEvent $event)
      {
          $user = $event->getUser();
          $user->addRole('CUSTOM_ROLE');
      }
      
    • Tag in services.yaml:
      tags: ['kernel.event_listener', 'firebase_auth.token_validated']
      
  3. Dynamic Config

    • Override default config via config/packages/firebase_authentication.yaml:
      firebase_authentication:
          strategies:
              bearer:
                  clock_skew: 120
                  issuer: https://securetoken.google.com/your-project-id
          providers:
              firebase:
                  user_class: App\Entity\CustomUser
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle