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

Simple Jwt Auth Laravel Package

raditzfarhan/simple-jwt-auth

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require raditzfarhan/simple-jwt-auth
    
  2. Register Service Provider (Lumen): Add to bootstrap/app.php:

    $app->register(RaditzFarhan\SimpleJWTAuth\JWTAuthServiceProvider::class);
    
  3. Configure Guards (in config/auth.php):

    'guards' => [
        'jwt' => [
            'driver' => 'simple-jwt-auth',
            'provider' => 'users',
        ],
    ],
    
  4. Publish Config (if needed):

    php artisan vendor:publish --provider="RaditzFarhan\SimpleJWTAuth\JWTAuthServiceProvider"
    

    (Note: The package lacks a default config file; check config/jwt.php if published.)

  5. First Use Case:

    • Login Route:
      use RaditzFarhan\SimpleJWTAuth\Facades\JWTAuth;
      
      Route::post('/login', function (Request $request) {
          $credentials = $request->only(['email', 'password']);
          $token = JWTAuth::attempt($credentials);
          return response()->json(['token' => $token]);
      });
      
    • Protected Route:
      Route::middleware('jwt')->get('/protected', function () {
          return response()->json(['message' => 'Access granted']);
      });
      

Implementation Patterns

Core Workflows

  1. Authentication:

    • Use JWTAuth::attempt($credentials) for login.
    • Use JWTAuth::once($credentials) for single-use tokens.
    • Use JWTAuth::user() to retrieve the authenticated user from the request.
  2. Token Management:

    • Generate Tokens:
      $token = JWTAuth::fromUser($user); // Manually generate for a user.
      
    • Refresh Tokens: The package doesn’t natively support refresh tokens; implement custom logic (e.g., store refresh tokens in DB and issue new JWTs on validation).
  3. Middleware Integration:

    • Apply the jwt middleware to routes:
      Route::middleware('jwt')->group(function () {
          // Protected routes
      });
      
    • Access the authenticated user in controllers:
      public function __construct() {
          $this->middleware('jwt');
      }
      
      public function protectedMethod() {
          $user = JWTAuth::user(); // Current user
      }
      
  4. Custom Guards:

    • Extend the guard for custom logic (e.g., role-based access):
      $user = JWTAuth::authenticate($request); // Manually authenticate
      if (!$user->hasRole('admin')) {
          abort(403);
      }
      

Integration Tips

  • Lumen-Specific:
    • Use Route::group(['middleware' => 'jwt'], ...) for route protection.
    • For API testing, include the token in the Authorization header:
      Authorization: Bearer <token>
      
  • Laravel-Specific:
    • Combine with Laravel’s built-in auth for hybrid systems:
      if (Auth::guard('jwt')->check()) {
          // JWT logic
      }
      
  • Token Storage:
    • Store tokens in HTTP-only cookies for web apps or localStorage for SPAs (ensure CORS is configured if using APIs).

Gotchas and Tips

Pitfalls

  1. No Built-in Refresh Tokens:

    • The package doesn’t handle refresh tokens. Implement a custom solution (e.g., store refresh tokens in the DB and validate them against a blacklist or expiry).
  2. Lumen-Only Focus:

    • While it works in Laravel, the package is primarily designed for Lumen. Some Laravel-specific features (e.g., session integration) may require manual adjustments.
  3. Limited Configuration:

    • No default jwt.php config file is published. Customize via:
      config(['jwt' => [
          'secret' => env('JWT_SECRET'),
          'ttl' => env('JWT_TTL', 60), // Token time-to-live in minutes
      ]]);
      
    • Ensure JWT_SECRET is set in .env.
  4. Token Expiry Handling:

    • Expired tokens return TokenExpiredException. Catch it globally in App\Exceptions\Handler:
      public function render($request, Throwable $exception) {
          if ($exception instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException) {
              return response()->json(['error' => 'Token expired'], 401);
          }
          return parent::render($request, $exception);
      }
      
  5. Middleware Conflicts:

    • If using Laravel’s auth middleware alongside jwt, ensure the jwt guard is properly configured in auth.php:
      'defaults' => [
          'guard' => 'jwt',
      ],
      

Debugging Tips

  1. Token Validation:

    • Decode tokens manually to debug:
      use Firebase\JWT\JWT;
      $decoded = JWT::decode($token, env('JWT_SECRET'), ['HS256']);
      
    • Ensure the JWT_SECRET matches the one used in the package.
  2. Logging:

    • Enable JWT logging in config/jwt.php:
      'logging' => true,
      
    • Check Laravel/Lumen logs for authentication errors.
  3. Common Errors:

    • TokenInvalidException: Token is malformed or tampered with.
    • TokenBlacklistedException: Token is revoked (if using a blacklist).
    • JWTException: General JWT library errors (e.g., invalid secret).

Extension Points

  1. Custom Claims:

    • Add custom claims to tokens:
      $token = JWTAuth::fromUser($user, [
          'custom_claim' => 'value',
      ]);
      
    • Access claims in middleware:
      $claims = JWTAuth::parseToken()->authenticate()->getPayload();
      
  2. Token Blacklisting:

    • Implement a blacklist table and middleware to invalidate tokens:
      // Middleware example
      public function handle($request, Closure $next) {
          if (JWTAuth::parseToken()->inBlacklist()) {
              abort(401, 'Token revoked');
          }
          return $next($request);
      }
      
  3. Custom User Resolver:

    • Override the user provider for non-Eloquent models:
      // In JWTAuthServiceProvider
      public function register() {
          $this->app->bind('auth.provider', function () {
              return new CustomUserProvider();
          });
      }
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor