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

Role Based Jwt Auth Laravel Package

shahzadbarkati/role-based-jwt-auth

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Run:

    composer require shahzadbarkati/role-based-jwt-auth
    php artisan vendor:publish --provider="ShahzadBarkati\RoleBasedJwtAuth\Providers\JwtAuthServiceProvider" --tag="config"
    php artisan vendor:publish --provider="ShahzadBarkati\RoleBasedJwtAuth\Providers\JwtAuthServiceProvider" --tag="migrations"
    

    Run migrations:

    php artisan migrate
    
  2. Configure Auth Guard Update config/auth.php to include the JWT guard:

    'guards' => [
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],
    
  3. First Use Case: Login Endpoint Send a POST request to /api/auth/login with:

    {
        "email": "user@example.com",
        "password": "password123"
    }
    

    Response includes JWT token and user data.


Implementation Patterns

Core Workflows

  1. Authentication Flow

    • Use Auth::guard('api')->attempt() for manual validation.
    • Leverage middleware @auth:api or role:admin for route protection.
  2. Role-Based Middleware Apply role checks in routes or controllers:

    Route::middleware(['auth:api', 'role:admin'])->group(function () {
        // Admin-only routes
    });
    

    Or in controllers:

    public function __construct() {
        $this->middleware('role:user|admin')->only(['index']);
    }
    
  3. Token Management

    • Refresh Tokens: Call /api/auth/refresh with the current token.
    • Logout: Invalidate tokens via /api/auth/logout or manually:
      Auth::guard('api')->user()->tokens()->delete();
      
  4. Password Resets

    • Trigger reset via /api/auth/forgot-password (returns 6-digit code).
    • Reset with /api/auth/reset-password (code + new password).

Integration Tips

  • Custom Roles: Extend the Role model or use pivot tables for many-to-many roles.
  • Token Blacklisting: Enable in config/jwt-auth.php to revoke tokens on logout.
  • Email Templates: Override resources/views/vendor/jwt-auth/emails for custom reset emails.
  • Testing: Use Auth::guard('api')->login($user) in tests to simulate auth.

Gotchas and Tips

Pitfalls

  1. Token Invalidation

    • By default, previous tokens are invalidated on login/refresh. Disable with:
      'invalidate_previous_tokens' => false,
      
    • Debugging: Check jwt_personal_access_tokens table for orphaned tokens.
  2. Role Assignment

    • Ensure users have roles assigned via user->roles()->attach($roleId).
    • Common Issue: Forgetting to sync roles after assignment:
      $user->roles()->sync([1, 2]); // Correct
      $user->roles()->attach(1);   // May not update if using many-to-many
      
  3. Password Reset Codes

    • Codes expire in 10 minutes by default. Customize in config/jwt-auth.php:
      'password_reset' => [
          'code_expiry_minutes' => 30,
      ],
      
    • Debugging: Verify password_reset_tokens table for expired codes.
  4. Middleware Conflicts

    • If using auth:api middleware, ensure the guard is properly configured in config/auth.php.
    • Fix: Add auth:api explicitly to routes or controllers.

Tips

  1. Custom Guards Extend the guard for additional logic:

    Auth::guard('api')->extend('custom', function ($app) {
        return new CustomJwtGuard($app['auth'], $app['request']);
    });
    
  2. Rate Limiting Apply rate limits to auth endpoints:

    Route::middleware(['throttle:6,1'])->group(function () {
        // Login/refresh routes
    });
    
  3. Logging Enable debug logging in config/jwt-auth.php:

    'debug' => env('APP_DEBUG', false),
    

    Check logs for token generation/validation issues.

  4. Testing Tokens Generate test tokens manually:

    $token = Auth::guard('api')->login($user);
    

    Or use the jwt-auth facade:

    use ShahzadBarkati\RoleBasedJwtAuth\Facades\JwtAuth;
    $token = JwtAuth::attempt(['email' => 'test@example.com', 'password' => 'password']);
    
  5. Performance

    • Cache role checks if roles rarely change:
      $user->getRoles()->cache();
      
    • Use select queries for token lookups:
      $token = Auth::guard('api')->user()->tokens()->select('id')->first();
      
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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