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

Symfony Bundle Laravel Package

betterauth/symfony-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require betterauth/symfony-bundle
    php bin/console better-auth:install
    
    • This auto-generates config files in config/packages/betterauth.yaml and creates a default User entity (extendable).
  2. Quick Configuration: Edit betterauth.yaml to define:

    better_auth:
        providers:
            google: true  # Enable OAuth providers
        features:
            two_factor: true  # Enable 2FA
        session:
            enabled: true    # Session-based auth
    
  3. First Use Case:

    • Run the feature setup with a preset (e.g., full for all features):
      php bin/console better-auth:setup-features --preset=full --with-controllers --migrate
      
    • Verify routes:
      php bin/console debug:router | grep auth
      
    • Test the /auth/login route (generated by --with-controllers).

Implementation Patterns

Core Workflows

  1. Authentication Modes:

    • Session Mode: Use better_auth.session for traditional web apps. Configure in betterauth.yaml:
      session:
          enabled: true
          cookie_secure: true  # HTTPS-only
      
    • API Mode: Use better_auth.api for stateless APIs. Example:
      api:
          enabled: true
          token_ttl: 3600  # 1-hour tokens
      
    • Hybrid Mode: Combine both for SPAs or progressive enhancement:
      hybrid:
          enabled: true
          session_ttl: 86400
          api_ttl: 3600
      
  2. OAuth Integration:

    • Enable providers in betterauth.yaml:
      providers:
          google:
              enabled: true
              client_id: "%env(GOOGLE_CLIENT_ID)%"
              client_secret: "%env(GOOGLE_CLIENT_SECRET)%"
          github: true
      
    • Use the generated controller (/auth/oauth/{provider}) or call the service directly:
      $auth = $this->get('better_auth.auth');
      $user = $auth->authenticateWithOAuth('google', $request);
      
  3. Two-Factor Authentication (2FA):

    • Enable in config:
      features:
          two_factor:
              enabled: true
              method: totp  # or 'backup_codes'
      
    • Trigger 2FA during login:
      $auth->requireTwoFactor($user);  // Redirects to 2FA flow
      
  4. Token Rotation (API):

    • Automatically rotate tokens on refresh:
      api:
          token_rotation:
              enabled: true
              max_tokens: 3
      
    • Manually refresh a token:
      $newToken = $auth->refreshToken($currentToken);
      
  5. Multi-Tenant Support (Optional):

    • Enable in config:
      multi_tenant:
          enabled: true
          tenant_field: tenant_id  # Field in User entity
      
    • Set tenant context:
      $auth->setTenantContext($tenantId);
      

Integration Tips

  1. Custom User Entity: Extend the default User entity (auto-generated at src/Entity/User.php):

    // src/Entity/CustomUser.php
    use BetterAuth\Symfony\Entity\User as BaseUser;
    
    class CustomUser extends BaseUser {
        #[ORM\Column]
        private string $customField;
    
        // Add getters/setters
    }
    

    Update betterauth.yaml:

    user_entity: App\Entity\CustomUser
    
  2. Event Listeners: Subscribe to auth events (e.g., AuthSuccessEvent):

    # config/services.yaml
    services:
        App\EventListener\AuthListener:
            tags:
                - { name: kernel.event_listener, event: better_auth.auth_success, method: onAuthSuccess }
    
  3. API Platform Integration: Secure API resources with the better_auth.api guard:

    # config/packages/api_platform.yaml
    api_platform:
        formats:
            jsonld:
                mime_types: ['application/ld+json']
        security:
            resource_class: ~
            guard: better_auth.api
    
  4. Custom Routes: Override default routes by defining your own controller and updating betterauth.yaml:

    routes:
        login: app_auth_login  # Custom route name
    

Gotchas and Tips

Pitfalls

  1. Database Migrations:

    • Always run --migrate with setup-features to avoid schema mismatches:
      php bin/console better-auth:setup-features --preset=full --migrate
      
    • If migrating later, use:
      php bin/console doctrine:migrations:execute latest --em=better_auth
      
  2. Token Storage:

    • API tokens are stored in the better_auth_token table by default. Ensure this table exists or configure a custom storage:
      api:
          token_storage:
              table: custom_token_table
      
  3. Session vs. API Conflicts:

    • Avoid mixing session and API modes without hybrid enabled. Configure explicitly:
      session:
          enabled: false  # Disable if using API-only
      
  4. OAuth Redirect URIs:

    • Ensure your OAuth provider’s redirect URI matches the generated route (e.g., https://yourapp.com/auth/oauth/google/callback). Configure in betterauth.yaml:
      providers:
          google:
              redirect_uri: "%env(AUTH_REDIRECT_URI)%"
      
  5. 2FA Backup Codes:

    • Backup codes are stored in the better_auth_2fa_backup_code table. Regenerate codes via:
      $auth->regenerateBackupCodes($user);
      

Debugging

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

    handlers:
        better_auth:
            type: stream
            path: "%kernel.logs_dir%/better_auth.log"
            level: debug
    
  2. Common Errors:

    • "User not found": Verify user_entity in betterauth.yaml points to a valid Doctrine entity.
    • OAuth failures: Check client_id/client_secret and redirect URIs in provider configs.
    • Token invalid: Ensure api.token_ttl is not set too low (default: 3600s).
  3. Testing: Use the better-auth:test:auth command to simulate auth flows:

    php bin/console better-auth:test:auth --provider=google --email=user@example.com
    

Extension Points

  1. Custom Authenticators: Implement BetterAuth\Symfony\Authenticator\AuthenticatorInterface:

    class CustomAuthenticator implements AuthenticatorInterface {
        public function authenticate(Request $request): ?User {
            // Custom logic
        }
    }
    

    Register in betterauth.yaml:

    authenticators:
        custom:
            class: App\Auth\CustomAuthenticator
            priority: 100
    
  2. Custom Providers: Extend BetterAuth\Symfony\Provider\OAuthProvider for new OAuth services:

    class CustomOAuthProvider extends OAuthProvider {
        protected function getAuthorizationUrl(): string {
            // Custom OAuth flow
        }
    }
    

    Configure in betterauth.yaml:

    providers:
        custom_provider:
            class: App\Auth\CustomOAuthProvider
            enabled: true
    
  3. Token Handlers: Override token logic by implementing BetterAuth\Symfony\Token\TokenHandlerInterface:

    class CustomTokenHandler implements TokenHandlerInterface {
        public function createToken(User $user): string {
            // Custom token generation
        }
    }
    

    Set in betterauth.yaml:

    api:
        token_handler: App\Auth\CustomTokenHandler
    
  4. Multi-Tenant Logic: Extend BetterAuth\Symfony\Tenant\TenantResolverInterface:

    class CustomTenantResolver implements TenantResolverInterface {
        public function resolve(Request $request): ?Tenant {
            // Custom tenant resolution (e.g., from subdomain)
        }
    }
    

    Configure:

    multi_tenant:
        resolver: App\Auth\CustomTenantResolver
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui