Weave 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 Laravel Package

adhocore/jwt

Lightweight PHP JWT library with simple encode/decode APIs, support for common algorithms (HS/RS), claims validation, and key handling. Designed for quick integration in apps and APIs with minimal dependencies and clear error reporting.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require adhocore/jwt
    

    No additional dependencies or complex configurations are required.

  2. First Use Case: Generate a JWT token with default settings:

    use Adhocore\Jwt\Jwt;
    
    $jwt = new Jwt();
    $token = $jwt->encode(['user_id' => 123], 'your-secret-key');
    echo $token; // Outputs a JWT string
    
  3. Where to Look First:

    • Source Code (if available) for edge cases.
    • Jwt class methods: encode(), decode(), verify(), and getPayload().
    • Default configuration (minimal, no external config files).

Implementation Patterns

Core Workflows

  1. Token Generation:

    $jwt = new Jwt();
    $token = $jwt->encode(
        ['user_id' => 123, 'role' => 'admin'],
        'your-secret-key',
        ['alg' => 'HS256', 'typ' => 'JWT'] // Optional headers
    );
    
    • Use HS256 (HMAC-SHA256) for symmetric signing (common for APIs).
    • For asymmetric signing (e.g., RS256), pass a private key as the second argument and use encodeWithKey().
  2. Token Verification/Decoding:

    $jwt = new Jwt();
    $payload = $jwt->decode($token, 'your-secret-key');
    // Or verify first (throws exception on failure):
    $jwt->verify($token, 'your-secret-key');
    $payload = $jwt->getPayload();
    
  3. Middleware Integration (Laravel):

    // app/Http/Middleware/VerifyJwt.php
    public function handle($request, Closure $next) {
        $jwt = new Jwt();
        try {
            $jwt->verify($request->bearerToken(), config('jwt.secret'));
            $request->merge(['user' => $jwt->getPayload()]);
        } catch (\Exception $e) {
            abort(401, 'Invalid token');
        }
        return $next($request);
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        \App\Http\Middleware\VerifyJwt::class,
    ];
    
  4. Custom Claims: Add metadata to payloads for business logic:

    $token = $jwt->encode([
        'user_id' => 123,
        'exp' => time() + 3600, // Expiry (Unix timestamp)
        'custom_claim' => 'value'
    ], 'secret');
    
  5. Token Expiry Handling:

    // Set expiry in payload (seconds from now)
    $payload = ['user_id' => 123, 'exp' => time() + 3600];
    $token = $jwt->encode($payload, 'secret');
    
    // Decode and check expiry manually
    $decoded = $jwt->decode($token, 'secret');
    if (isset($decoded['exp']) && $decoded['exp'] < time()) {
        throw new \Exception('Token expired');
    }
    

Gotchas and Tips

Pitfalls

  1. Secret Key Management:

    • Hardcoding secrets in code violates security best practices. Use Laravel's .env:
      JWT_SECRET=your-strong-secret-key-here
      
    • Rotate keys periodically and invalidate old tokens.
  2. Algorithm Assumptions:

    • The library defaults to HS256 if no algorithm is specified. Always explicitly set the algorithm to avoid ambiguity:
      $token = $jwt->encode($payload, 'secret', ['alg' => 'HS256']);
      
  3. Payload Size Limits:

    • JWTs have a maximum size (~4KB). Avoid storing large data; use token claims for metadata and reference IDs for database lookups.
  4. Time Skew:

    • Clock skew (difference between server and client time) can cause premature token expiration. Add a buffer (e.g., 5 minutes) when setting exp claims:
      $payload['exp'] = time() + (3600 + 300); // 1 hour + 5 min buffer
      
  5. Error Handling:

    • decode() and verify() throw exceptions on failure. Catch specific exceptions (e.g., Adhocore\Jwt\Exception\InvalidToken) for granular error handling:
      try {
          $jwt->verify($token, 'secret');
      } catch (\Adhocore\Jwt\Exception\InvalidToken $e) {
          // Handle invalid token
      }
      

Debugging Tips

  1. Token Inspection: Use jwt.io to decode and inspect tokens manually for debugging.

  2. Logging: Log payloads and tokens (sanitized) for auditing:

    \Log::debug('JWT Payload', ['payload' => $jwt->getPayload()]);
    
  3. Testing: Mock the Jwt class in PHPUnit for isolated testing:

    $mockJwt = $this->createMock(Jwt::class);
    $mockJwt->method('decode')->willReturn(['user_id' => 123]);
    

Extension Points

  1. Custom Algorithms: Extend the library by implementing your own algorithm handler (advanced). The library supports HS256, HS384, HS512, RS256, RS384, and RS512 out of the box.

  2. Payload Validation: Add validation logic post-decoding:

    $payload = $jwt->decode($token, 'secret');
    if (!in_array($payload['role'], ['admin', 'editor'])) {
        throw new \Exception('Insufficient permissions');
    }
    
  3. Token Storage: For stateless APIs, store tokens in HTTP-only cookies or Authorization: Bearer headers. Avoid localStorage for security.

  4. Refresh Tokens: Implement a refresh token workflow:

    // Issue a short-lived access token + long-lived refresh token
    $accessToken = $jwt->encode(['exp' => time() + 3600], 'access-secret');
    $refreshToken = $jwt->encode(['exp' => time() + 86400], 'refresh-secret');
    
  5. Performance:

    • Reuse Jwt instances (stateless, thread-safe).
    • Cache decoded payloads if verification is frequent (e.g., in middleware).
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.
uni-method/symfony-lib
tacticmedia/scim-server-bundle
neika-ai/symfony-bundle
mattleads/agent-publishing-bundle
glavweb/framework-bundle
glavweb/extra-bundle
glavweb/api-bundle
glavweb/admin-bundle
adachsoft/api-version-bundle
elsayed85/laravel-api-exceptions
ouhssini/laravel-demo-mode
daworks/ncloud-outbound-mailer-driver
gp247/cms
ignibyte/aic-gates
nexa-merchant/blog
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
cgv/localized-resource