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

Laravel Jwt Auth Laravel Package

nikservik/laravel-jwt-auth

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nikservik/laravel-jwt-auth
    php artisan vendor:publish --provider="Nikservik\LaravelJwtAuth\LaravelJwtAuthServiceProvider" --tag=migrations
    php artisan migrate
    
    • Verify the jwt_users table exists (checks for id, name, email, password, remember_token, api_token, token_expires_at).
  2. First Use Case:

    • Register a User:
      use Nikservik\LaravelJwtAuth\Facades\JwtAuth;
      
      $user = JwtAuth::register([
          'name' => 'Test User',
          'email' => 'test@example.com',
          'password' => 'password123',
      ]);
      
    • Login and Generate Token:
      $token = JwtAuth::attempt(['email' => 'test@example.com', 'password' => 'password123']);
      
    • Authenticate Requests: Add middleware to app/Http/Kernel.php:
      'api' => [
          \Nikservik\LaravelJwtAuth\Http\Middleware\VerifyJwtToken::class,
      ],
      
      Then protect routes:
      Route::middleware(['api'])->group(function () {
          Route::get('/protected', function () {
              return response()->json(['message' => 'Protected route']);
          });
      });
      

Implementation Patterns

Core Workflows

  1. User Management:

    • Registration: Use JwtAuth::register() with validated input. Extend the JwtUser model if custom fields are needed.
    • Login/Logout:
      // Login
      $token = JwtAuth::attempt($credentials);
      
      // Logout (revoke token)
      JwtAuth::logout();
      
    • Token Refresh:
      $refreshedToken = JwtAuth::refresh($oldToken);
      
  2. Protected Routes:

    • Access the authenticated user in controllers:
      public function __construct() {
          $this->middleware('api');
      }
      
      public function protectedRoute() {
          $user = JwtAuth::user(); // Returns the authenticated JwtUser model
      }
      
  3. Custom Claims: Add metadata to tokens (e.g., roles):

    $token = JwtAuth::fromUser($user, [
        'role' => 'admin',
        'is_active' => true
    ]);
    

Integration Tips

  • Laravel Sanctum/Passport: Use alongside Sanctum for session-based auth or Passport for OAuth2. Avoid mixing token storage (e.g., don’t store JWTs in Sanctum’s personal_access_tokens table).

  • Rate Limiting: Combine with Laravel’s throttle middleware to limit JWT-authenticated requests:

    Route::middleware(['api', 'throttle:60,1'])->group(...);
    
  • Testing: Use JwtAuth::setToken($token) in tests to simulate authentication:

    $this->actingAs(JwtAuth::user(), 'api');
    

Gotchas and Tips

Pitfalls

  1. Token Storage:

    • The package stores tokens in the jwt_users table (api_token and token_expires_at). Never store sensitive data in these fields. Use custom claims for metadata instead.
  2. Migration Conflicts:

    • If you’ve customized the users table, the jwt_users migration might fail. Manually adjust the migration or drop the table and republish:
      php artisan migrate:fresh --env=testing
      
  3. Password Hashing:

    • Ensure your App\User model (or JwtUser) uses Laravel’s HasApiTokens trait and Notifiable. The package assumes BCrypt hashing via Laravel’s Hash facade.
  4. Token Expiry:

    • Default expiry is 1 hour. Override in .env:
      JWT_TTL=3600  # 1 hour in seconds
      
    • Warning: Short TTLs increase login frequency but add overhead. Balance security and UX.

Debugging

  1. Token Validation Errors:

    • Check for TokenInvalidException or TokenExpiredException. Log the raw error:
      try {
          $user = JwtAuth::parseToken()->authenticate();
      } catch (\Nikservik\LaravelJwtAuth\Exceptions\TokenExpiredException $e) {
          Log::error('Token expired: ' . $e->getMessage());
      }
      
  2. Middleware Bypass:

    • If routes skip JWT verification, ensure:
      • The middleware is registered in Kernel.php.
      • Routes use the api middleware group.
      • No auth:api middleware conflicts (this package uses api by default).
  3. Locale/Translation Issues:

    • Publish translations if using non-English:
      php artisan vendor:publish --tag=translations
      
    • Override specific strings in resources/lang/{locale}/jwt.php.

Extension Points

  1. Custom User Model:

    • Extend the JwtUser model (published in app/Models/JwtUser.php after publishing views):
      class CustomUser extends JwtUser {
          protected $fillable = ['custom_field'];
      }
      
    • Bind the model in AuthServiceProvider:
      public function boot() {
          $this->app['Nikservik\LaravelJwtAuth\JwtAuth']->setUserModel(CustomUser::class);
      }
      
  2. Token Blacklisting:

    • Implement a revokeToken() method in JwtUser to manually invalidate tokens:
      public function revokeToken() {
          $this->api_token = null;
          $this->save();
      }
      
  3. Email Templates:

    • Customize registration/login emails by overriding the published views in resources/views/vendor/jwt-auth/emails/. Key files:
      • registration.blade.php
      • login.blade.php
      • password_reset.blade.php (if using password reset).
  4. API Token Rotation:

    • Rotate tokens on login by clearing the old token:
      JwtAuth::logout(); // Revokes current token
      $newToken = JwtAuth::attempt($credentials); // Issues a new one
      
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.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat