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

Auth0 Php Laravel Package

auth0/auth0-php

Auth0 PHP SDK for integrating Auth0 Authentication and Management APIs. Build login/logout flows, validate tokens, and manage users, roles, and applications. Works with any PHP app, with tailored SDKs available for Laravel, Symfony, and WordPress.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Laravel Integration
1. **Install the package** via Composer:
   ```bash
   composer require auth0/auth0-php
  1. Publish the config (if using Laravel-specific features):
    php artisan vendor:publish --provider="Auth0\SDK\Auth0ServiceProvider"
    
  2. Configure Auth0 in .env:
    AUTH0_DOMAIN=your-auth0-domain.auth0.com
    AUTH0_CLIENT_ID=your-client-id
    AUTH0_CLIENT_SECRET=your-client-secret
    AUTH0_COOKIE_SECRET=openssl rand -hex 32
    AUTH0_CALLBACK_URL=http://your-app.test/auth0/callback
    AUTH0_LOGOUT_URL=http://your-app.test
    
  3. First use case: Add a login route in routes/web.php:
    use Auth0\SDK\Auth0;
    use Auth0\SDK\Configuration\SdkConfiguration;
    
    Route::get('/login', function () {
        $config = new SdkConfiguration(
            domain: env('AUTH0_DOMAIN'),
            clientId: env('AUTH0_CLIENT_ID'),
            clientSecret: env('AUTH0_CLIENT_SECRET'),
            cookieSecret: env('AUTH0_COOKIE_SECRET')
        );
        $auth0 = new Auth0($config);
        return redirect($auth0->login());
    });
    

Implementation Patterns

Authentication Workflow

  1. Login Flow:
    // Middleware (e.g., `Auth0Middleware`)
    public function handle(Request $request, Closure $next) {
        $auth0 = app(Auth0::class);
        $credentials = $auth0->getCredentials();
    
        if (!$credentials || $credentials->accessTokenExpired) {
            return redirect($auth0->login());
        }
        return $next($request);
    }
    
  2. Callback Handling:
    Route::get('/auth0/callback', function () {
        $auth0 = app(Auth0::class);
        if ($auth0->getExchangeParameters()) {
            $auth0->exchange();
            return redirect('/dashboard');
        }
        return redirect('/login');
    });
    
  3. User Data Access:
    $user = $auth0->getCredentials()?->user;
    // Use $user->email, $user->sub, etc.
    

Management API Integration

  1. Initialize Management API Client:
    use Auth0\SDK\Management\Auth0ManagementClient;
    
    $managementClient = new Auth0ManagementClient(
        domain: env('AUTH0_DOMAIN'),
        clientId: env('AUTH0_CLIENT_ID'),
        clientSecret: env('AUTH0_CLIENT_SECRET'),
        scope: ['read:users', 'update:users']
    );
    
  2. Fetch Users with Pagination (v9):
    $users = $managementClient->users->listUsers();
    foreach ($users as $user) {
        // Process user
    }
    
  3. Create a User:
    $newUser = $managementClient->users->createUser([
        'connection' => 'Username-Password-Authentication',
        'email' => 'user@example.com',
        'password' => 'securepassword',
        'given_name' => 'John',
        'family_name' => 'Doe'
    ]);
    

Token Validation (Stateless APIs)

  1. Validate API Tokens:
    use Auth0\SDK\Auth0;
    
    $auth0 = new Auth0(
        domain: env('AUTH0_DOMAIN'),
        clientId: env('AUTH0_CLIENT_ID'),
        clientSecret: env('AUTH0_CLIENT_SECRET')
    );
    
    $isValid = $auth0->validateToken($request->bearerToken);
    if (!$isValid) {
        abort(401, 'Invalid token');
    }
    

Custom Claims and Extensions

  1. Add Custom Claims to Tokens:
    $auth0 = app(Auth0::class);
    $auth0->getCredentials()->addCustomClaim('custom_role', 'admin');
    

Gotchas and Tips

Common Pitfalls

  1. Cookie Secret Mismanagement:

    • Issue: Forgetting to set a secure cookieSecret (e.g., generated via openssl rand -hex 32) can lead to session hijacking.
    • Fix: Always use a 32-byte random string and store it securely (e.g., .env).
  2. Callback URL Mismatch:

    • Issue: Auth0 redirects fail if the callback URL in the SDK doesn’t match the one configured in the Auth0 Dashboard.
    • Fix: Ensure AUTH0_CALLBACK_URL in .env matches the exact URL in Auth0 Dashboard (including http/https and trailing slashes).
  3. Token Expiry Handling:

    • Issue: Silent token expiry can cause 401 errors in APIs.
    • Fix: Use middleware to refresh tokens or validate expiry:
      $credentials = $auth0->getCredentials();
      if ($credentials && $credentials->accessTokenExpired) {
          $auth0->refreshToken();
      }
      
  4. Management API Scopes:

    • Issue: Missing scopes (e.g., read:users) cause 403 errors.
    • Fix: Explicitly define scopes when initializing the client:
      $managementClient = new Auth0ManagementClient(
          // ...
          scope: ['read:users', 'update:users']
      );
      

Debugging Tips

  1. Enable Verbose Logging:

    $config = new SdkConfiguration(
        // ...
        debug: true
    );
    
    • Logs will appear in storage/logs/laravel.log.
  2. Token Debugging:

    • Decode JWTs manually to inspect claims:
      composer require firebase/php-jwt
      
      use Firebase\JWT\JWT;
      $decoded = JWT::decode($token, new \Firebase\JWT\Key('...', 'HS256'));
      
  3. Management API Errors:

    • Check the error and error_description fields in responses:
      try {
          $user = $managementClient->users->getUser('user_id');
      } catch (\Auth0\SDK\Exception\SdkException $e) {
          dd($e->getResponse()->getBody());
      }
      

Extension Points

  1. Custom HTTP Client:

    • Override the default HTTP client for retries or monitoring:
      $httpClient = new \GuzzleHttp\Client([
          'timeout' => 10,
          'headers' => ['User-Agent' => 'MyApp/1.0']
      ]);
      $config = new SdkConfiguration(
          // ...
          httpClient: $httpClient
      );
      
  2. Middleware for Token Refresh:

    • Create a Laravel middleware to auto-refresh expired tokens:
      public function handle($request, Closure $next) {
          $auth0 = app(Auth0::class);
          if ($auth0->getCredentials()?->accessTokenExpired) {
              $auth0->refreshToken();
          }
          return $next($request);
      }
      
  3. V9 Migration:

    • Breaking Change: v9’s Management API uses strong typing and auto-generated models.
    • Tip: Use php artisan vendor:publish --tag=auth0-migrations if the package provides migration helpers.
  4. Custom User Attributes:

    • Extend the User model to include Auth0-specific fields:
      class Auth0User extends User {
          public function getAuth0Id(): string {
              return $this->auth0_id ?? '';
          }
      }
      

Performance Optimizations

  1. Cache Management API Responses:

    $users = Cache::remember('auth0_users', now()->addHours(1), function () {
        return $managementClient->users->listUsers();
    });
    
  2. Lazy-Load User Data:

    • Avoid fetching all user data upfront. Use select() for specific fields:
      $user = $managementClient->users->getUser('user_id', ['fields' => ['email', 'name']]);
      
  3. Batch Operations:

    • Use bulk endpoints (e.g., deleteUsers) for large-scale operations to reduce API calls.

Security Best Practices

  1. Avoid Hardcoding Secrets:

    • Always use Laravel’s .env for sensitive data (e.g., AUTH0_CLIENT_SECRET).
  2. Secure Cookie Settings:

    $config = new SdkConfiguration(
        // ...
        cookieSettings: [
            'secure' => true,       // HTTPS only
            'httpOnly' => true,     // Prevent JS access
            'sameSite' => 'Lax',    // CSRF protection
        ]
    );
    
  3. Rate Limiting:

    • Implement middleware to throttle Auth0 API calls:
      use Illuminate\Cache\RateLimiting
      
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.
terminal42/code-quality-tools
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