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

auth0/symfony

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for First Use

  1. Install the package:

    composer require auth0/symfony
    
  2. Configure Auth0:

    • Create a Regular Web Application in Auth0 Dashboard.
    • Set Token Endpoint Authentication Method to POST.
    • Configure Allowed Callback URLs (e.g., http://localhost:8000/callback) and Allowed Logout URLs (e.g., http://localhost:8000/login).
    • Note your Domain, Client ID, and Client Secret.
  3. Configure Symfony:

    • Add auth0.yaml to config/packages/ with environment variables for domain, client_id, client_secret, and routes.
    • Update .env.local with Auth0 credentials and route paths (e.g., AUTH0_ROUTE_CALLBACK=callback).
    • Register the bundle in config/bundle.php:
      Auth0\Symfony\Auth0Bundle::class => ['all' => true],
      
    • Add helper routes in config/routes.yaml:
      login:
        path: /login
        controller: Auth0\Symfony\Controllers\AuthenticationController::login
      callback:
        path: /callback
        controller: Auth0\Symfony\Controllers\AuthenticationController::callback
      
  4. Test Authentication:

    • Visit /login to trigger Auth0 login.
    • After authentication, the user is redirected to /private (configured in .env.local).
    • Verify user data in a controller:
      public function private(): Response {
          return new Response(print_r($this->getUser(), true));
      }
      

Implementation Patterns

Core Workflows

  1. Session-Based Authentication (Web Apps):

    • Use the auth0.authenticator in security.yaml for stateful routes (e.g., /private).
    • Example security.yaml:
      firewalls:
        auth0:
          pattern: ^/private
          provider: auth0_provider
          custom_authenticators: [auth0.authenticator]
      
    • Redirects:
      • Success → AUTH0_ROUTE_SUCCESS (e.g., /private).
      • Failure → AUTH0_ROUTE_FAILURE (e.g., /public).
  2. Token-Based Authentication (APIs):

    • Use auth0.authorizer for stateless APIs (e.g., /api).
    • Example security.yaml:
      firewalls:
        api:
          pattern: ^/api
          stateless: true
          custom_authenticators: [auth0.authorizer]
      
    • Roles:
      • ROLE_USING_TOKEN: Automatically added to requests with valid tokens.
      • Custom roles (e.g., ROLE_READ_MESSAGES) via token scopes.
  3. User Data Access:

    • Retrieve user claims in controllers:
      $user = $this->getUser(); // Auth0User object
      $email = $user->getEmail();
      $name = $user->getName();
      
    • Access raw JWT payload:
      $jwtPayload = $user->getJwtPayload();
      
  4. Management API:

    • Use Auth0\SDK\Auth0 service for API calls:
      $auth0 = $container->get('auth0.sdk');
      $users = $auth0->users()->listUsers();
      
    • Cache management tokens with management_token_cache in auth0.yaml.
  5. Backchannel Logout:

    • Add a POST route for Auth0’s logout webhooks:
      backchannel:
        path: /backchannel
        controller: Auth0\Symfony\Controllers\BackchannelController::handle
      
    • Configure Auth0 tenant to send logout requests to this endpoint.

Integration Tips

  1. Custom User Provider:

    • Extend Auth0\Symfony\Security\UserProvider to map Auth0 users to your entities:
      class CustomUserProvider extends Auth0UserProvider {
          public function loadUserByUsername($username) {
              // Custom logic (e.g., fetch from DB)
          }
      }
      
    • Register in security.yaml:
      providers:
        custom_provider:
          id: App\Security\CustomUserProvider
      
  2. Role Mapping:

    • Map Auth0 roles to Symfony roles in Auth0UserProvider:
      public function getRoles() {
          return ['ROLE_ADMIN']; // Based on Auth0 user metadata
      }
      
  3. Caching:

    • Configure Redis for JWKS and token caching:
      auth0:
        sdk:
          token_cache: cache.auth0_token_cache
          management_token_cache: cache.auth0_management_token_cache
      
    • Define cache pools in cache.yaml:
      pools:
        auth0_token_cache: { adapter: cache.adapter.redis }
      
  4. Error Handling:

    • Catch Auth0\SDK\Exception\Auth0Exception for API errors:
      try {
          $auth0->users()->delete($userId);
      } catch (Auth0Exception $e) {
          // Log or handle error
      }
      
  5. Testing:

    • Mock Auth0\SDK\Auth0 in tests:
      $auth0 = $this->createMock(Auth0::class);
      $auth0->method('getUserInfo')->willReturn(['sub' => 'user123']);
      $container->set('auth0.sdk', $auth0);
      

Gotchas and Tips

Pitfalls

  1. Environment Variables:

    • Issue: Forgetting to add .env.local to .gitignore or committing secrets.
    • Fix: Use env() in auth0.yaml and validate presence:
      domain: "%env(AUTH0_DOMAIN)%"
      
      Add validation in config/services.yaml:
      parameters:
        env(AUTH0_DOMAIN): 'required'
      
  2. Route Mismatches:

    • Issue: Auth0 callback/logout URLs not matching configured routes.
    • Fix: Double-check Allowed Callback URLs and Allowed Logout URLs in Auth0 Dashboard.
    • Debug: Enable Symfony’s debug:router to verify route paths.
  3. Token Expiry:

    • Issue: Silent failures when tokens expire (e.g., during API calls).
    • Fix: Implement retry logic with exponential backoff:
      try {
          $auth0->users()->listUsers();
      } catch (TokenExpiredException $e) {
          $auth0->refreshToken();
          retry();
      }
      
  4. CORS for APIs:

    • Issue: CORS errors when calling Auth0 APIs from frontend.
    • Fix: Configure CORS in Symfony or proxy requests via backend.
  5. Backchannel Logout:

    • Issue: Missing /backchannel route causes logout failures.
    • Fix: Ensure the route is publicly accessible and Auth0’s Logout URI is correctly configured.

Debugging Tips

  1. Enable SDK Logging:

    • Add to config/packages/monolog.yaml:
      handlers:
        auth0:
          type: stream
          path: "%kernel.logs_dir%/auth0.log"
          level: debug
          channels: ["auth0"]
      
    • Log SDK events:
      $auth0->getLogger()->debug('Event', ['data' => $event]);
      
  2. Validate JWTs Manually:

    • Use Auth0’s JWT Debugger to verify tokens.
    • Check JWKS endpoint:
      curl https://{domain}/.well-known/jwks.json
      
  3. Common Errors:

    • InvalidClient: Incorrect client_id/client_secret in Auth0 Dashboard.
    • InvalidRedirectURI: Callback URL not whitelisted in Auth0.
    • TokenExpired: Token cache not refreshed (enable token_cache).

Extension Points

  1. Custom Authenticator:

    • Extend Auth0Authenticator to add pre/post-login logic:
      class CustomAuthenticator extends Auth0Authenticator {
          public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName) {
              // Log or update user data
              return parent::onAuthenticationSuccess($request, $token, $firewallName);
          }
      }
      
    • Register in security.yaml:
      custom_authenticators: [App\Security\CustomAuthenticator]
      
  2. Dynamic Scopes:

    • Override getScopes() in Auth0Authenticator to fetch scopes dynamically:
      public function getScopes() {
          return ['openid', 'profile', 'custom:' . $this->getUserId()];
      }
      
  3. Custom User Claims:

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