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

duylecampos/jwt-oauth2-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require duylecampos/jwt-oauth2-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        DuyleCampos\JwtOauth2Bundle\DuyleCamposJwtOauth2Bundle::class => ['all' => true],
    ];
    
  2. Publish Config

    php artisan vendor:publish --provider="DuyleCampos\JwtOauth2Bundle\DuyleCamposJwtOauth2Bundle" --tag="config"
    

    Edit config/jwt_oauth2.php for your OAuth2 provider (e.g., Auth0, Okta).

  3. First Use Case: Authenticate via OAuth2 Add middleware to app/Http/Kernel.php:

    'api' => [
        \DuyleCampos\JwtOauth2Bundle\Http\Middleware\JwtOauth2::class,
    ],
    

    Test with a protected route:

    Route::middleware(['api'])->get('/user', function () {
        return auth()->user();
    });
    

Implementation Patterns

Workflows

  1. Token Validation Automatically validates JWT tokens from the Authorization: Bearer <token> header.

    if (auth()->check()) {
        $user = auth()->user(); // Returns decoded user data
    }
    
  2. Custom Claims Handling Extend the bundle to handle custom claims:

    // In a service provider
    $this->app->bind(\DuyleCampos\JwtOauth2Bundle\Services\JwtDecoder::class, function ($app) {
        return new CustomJwtDecoder($app['config']['jwt_oauth2']);
    });
    
  3. OAuth2 Provider Switching Update config/jwt_oauth2.php to switch providers (e.g., Auth0 → Okta):

    providers:
        auth0:
            enabled: false
        okta:
            enabled: true
            client_id: "your_okta_client_id"
            client_secret: "your_okta_secret"
            domain: "your-okta-domain.okta.com"
    
  4. Integration with Laravel Auth Use the bundle’s User model trait for seamless auth:

    use DuyleCampos\JwtOauth2Bundle\Traits\HasJwtOauth2;
    
    class User extends Authenticatable {
        use HasJwtOauth2;
    }
    
  5. Token Refresh Implement a refresh token endpoint:

    Route::post('/refresh-token', function () {
        $token = request()->input('refresh_token');
        return response()->json([
            'access_token' => auth()->refresh($token),
        ]);
    });
    

Gotchas and Tips

Pitfalls

  1. Token Expiry Handling

    • The bundle does not auto-refresh expired tokens. Implement a try-catch for TokenExpiredException:
      try {
          $user = auth()->user();
      } catch (\DuyleCampos\JwtOauth2Bundle\Exceptions\TokenExpiredException $e) {
          return response()->json(['error' => 'Token expired'], 401);
      }
      
  2. Config Overrides

    • Ensure config/jwt_oauth2.php is correctly published. Missing keys (e.g., client_secret) will throw InvalidArgumentException.
  3. Middleware Order

    • Place JwtOauth2 middleware before auth:api to avoid conflicts:
      'api' => [
          \DuyleCampos\JwtOauth2Bundle\Http\Middleware\JwtOauth2::class,
          \App\Http\Middleware\CheckForApiToken::class, // Laravel's default
      ],
      
  4. Debugging Token Decoding

    • Enable verbose logging in config/jwt_oauth2.php:
      debug: true
      
    • Check logs for decoded payloads or errors in storage/logs/laravel.log.

Tips

  1. Custom User Mapping Map OAuth2 user data to your Laravel User model:

    // In config/jwt_oauth2.php
    user_mapping: [
        'email' => 'email',
        'name' => 'name',
        'custom_field' => 'oauth_id',
    ]
    
  2. Rate Limiting Combine with Laravel’s rate limiting:

    Route::middleware(['throttle:60,1', 'api'])->get('/user');
    
  3. Testing Use Http\Testing\Middleware\JwtOauth2 in PHPUnit:

    $response = $this->withHeaders([
        'Authorization' => 'Bearer valid.jwt.token',
    ])->get('/user');
    
  4. Extension Points

    • Override the JwtDecoder to add custom logic (e.g., role validation):
      public function decode($token) {
          $decoded = parent::decode($token);
          if (!$decoded['roles'] || !in_array('admin', $decoded['roles'])) {
              throw new \RuntimeException('Insufficient permissions');
          }
          return $decoded;
      }
      
  5. CORS Configuration Ensure your CORS middleware allows the Authorization header:

    $headers = [
        'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization',
    ];
    
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