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

Jwt Auth Bundle Laravel Package

auth0/jwt-auth-bundle

Symfony bundle for Auth0 authentication and management APIs. Supports PHP 8.1+ and Symfony 6.4/7/8. Install via Composer, configure domain/client credentials and callback/logout URLs, then use the SDK for login, tokens, and user sessions.

View on GitHub
Deep Wiki
Context7
## Getting Started

### First Steps for a Laravel Developer
1. **Installation**
   ```bash
   composer require auth0/symfony

Note: While this is a Symfony package, Laravel developers can use it via a bridge like spatie/laravel-symfony or by manually integrating the core Auth0 SDK logic.

  1. Configuration

    • Create .env entries for AUTH0_DOMAIN, AUTH0_CLIENT_ID, and AUTH0_CLIENT_SECRET.
    • Set up routes for /login, /callback, and /logout (see Implementation Patterns for Laravel-specific routing).
  2. First Use Case: Authenticate a User

    • Use the Auth0\SDK\Auth0 class to validate tokens or trigger login flows.
    • Example:
      use Auth0\SDK\Auth0;
      
      $auth0 = new Auth0([
          'domain' => env('AUTH0_DOMAIN'),
          'client_id' => env('AUTH0_CLIENT_ID'),
          'client_secret' => env('AUTH0_CLIENT_SECRET'),
      ]);
      
      // Redirect to Auth0 login
      return redirect()->to($auth0->login(['redirect_uri' => route('callback')]));
      

Implementation Patterns

1. Laravel-Specific Workflows

Session-Based Authentication (SPA-like)

  • Use Laravel’s middleware to protect routes:
    // app/Http/Middleware/Auth0Middleware.php
    public function handle($request, Closure $next) {
        if (!$request->user()) {
            $auth0 = new Auth0([...]);
            return redirect()->to($auth0->login(['redirect_uri' => route('callback')]));
        }
        return $next($request);
    }
    
  • Register middleware in app/Http/Kernel.php:
    protected $routeMiddleware = [
        'auth0' => \App\Http\Middleware\Auth0Middleware::class,
    ];
    

Token-Based API Authentication

  • Validate tokens in API requests:
    use Auth0\SDK\Auth0;
    
    $auth0 = new Auth0([...]);
    $token = $request->bearerToken();
    
    try {
        $user = $auth0->getUser($token);
        // Attach user to request or validate scopes
    } catch (\Exception $e) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }
    

2. Common Patterns

Handling the Callback

  • Decode the Auth0 token and create a Laravel user session:
    // routes/web.php
    Route::get('/callback', function () {
        $auth0 = new Auth0([...]);
        $user = $auth0->getUser(); // Uses code from Auth0 redirect
        Auth::loginUsingId($user['sub']); // Custom logic to link Auth0 user to Laravel
        return redirect()->to(route('private'));
    });
    

Management API Calls

  • Use the Management API for user/data operations:
    $managementApi = $auth0->managementApi();
    $users = $managementApi->users()->listUsers();
    

Logout Handling

  • Clear Laravel session + trigger Auth0 logout:
    Route::get('/logout', function () {
        Auth::logout();
        $auth0 = new Auth0([...]);
        return redirect()->to($auth0->logout(['returnTo' => route('home')]));
    });
    

3. Integration Tips

  • Laravel Caching: Use Laravel’s cache drivers for token_cache and management_token_cache:
    # config/auth0.yaml (Laravel-style)
    token_cache: cache.auth0
    management_token_cache: cache.auth0_management
    
  • Custom User Provider: Extend Laravel’s User model to sync Auth0 data:
    class User extends Authenticatable {
        public static function findForPassport($identifier) {
            $auth0 = new Auth0([...]);
            $user = $auth0->getUser($identifier);
            return self::firstOrCreate(['email' => $user['email']], $user);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Token Validation Failures

    • Ensure AUTH0_DOMAIN includes https:// (e.g., https://your-domain.auth0.com).
    • Debug with:
      try {
          $auth0->getUser($token);
      } catch (\Auth0\SDK\Exception\CoreException $e) {
          Log::error($e->getMessage());
      }
      
  2. CSRF Issues in Callback

    • Laravel’s CSRF middleware may block the Auth0 callback. Exclude it:
      Route::get('/callback', [...])->middleware('web')->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class);
      
  3. Session vs. Token Confusion

    • Session-based auth: Use auth0.authenticator (Symfony) or Laravel middleware.
    • Token-based auth: Use auth0.authorizer (Symfony) or validate tokens manually in APIs.

Debugging Tips

  • Enable Auth0 SDK Logging:
    $auth0 = new Auth0([...], [
        'log_level' => \Monolog\Logger::DEBUG,
        'logger' => new \Monolog\Handler\StreamHandler(storage_path('logs/auth0.log')),
    ]);
    
  • Check Token Claims:
    $jwt = (new \Firebase\JWT\JWT())->decode($token, $auth0->getPublicKey(), ['HS256']);
    dd($jwt); // Inspect claims for debugging
    

Extension Points

  1. Custom User Mapping

    • Override the default user provider to map Auth0 users to Laravel models:
      use Auth0\SDK\User as Auth0User;
      
      class CustomUserProvider implements UserProviderInterface {
          public function loadUserByIdentifier($identifier) {
              $auth0 = new Auth0([...]);
              $user = $auth0->getUser($identifier);
              return User::firstOrNew(['email' => $user['email']]);
          }
      }
      
  2. Backchannel Logout

    • Add a Laravel route for Auth0’s backchannel logout:
      Route::post('/backchannel', function (Request $request) {
          $auth0 = new Auth0([...]);
          $auth0->backchannelLogout()->handle($request);
          return response()->json(['success' => true]);
      });
      
    • Configure Auth0 Dashboard to send logout requests to /backchannel.
  3. Rate Limiting

    • Cache Management API tokens aggressively:
      management_token_cache: cache.auth0_management # Use Redis for high traffic
      

Laravel-Specific Quirks

  • Laravel’s auth() Helper: Avoid mixing with Auth0’s session. Use Auth::user() for Laravel users and $request->user() for Auth0 tokens.
  • Passport Integration: If using Laravel Passport, validate Auth0 tokens against Passport’s PersonalAccessClient:
    $token = $auth0->getAccessToken();
    $client = PersonalAccessClient::findOrFail(1);
    $client->tokens()->create(['token' => $token, 'abilities' => ['*']]);
    

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