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

Php Jwt Laravel Package

fproject/php-jwt

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require fproject/php-jwt
    

    Add to composer.json if not using autoloading:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Firebase\\JWT\\": "vendor/fproject/php-jwt/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Decoding a JWT

    use Firebase\JWT\JWT;
    
    $token = 'your.jwt.token.here';
    $decoded = JWT::decode($token, 'secret_key', ['HS256']);
    
  3. Where to Look First

    • Source Code (if available) for edge cases.
    • src/ directory for core classes (JWT.php, Key.php, ExpiredException.php, etc.).
    • JWT.io for debugging token structure.

Implementation Patterns

Core Workflows

  1. Encoding Tokens

    $payload = [
        'iss' => 'your-app',
        'iat' => time(),
        'data' => ['user_id' => 123]
    ];
    $token = JWT::encode($payload, 'secret_key', 'HS256');
    
  2. Decoding with Validation

    try {
        $decoded = JWT::decode($token, 'secret_key', ['HS256']);
        // $decoded is a stdClass; cast to array if needed:
        $data = (array) $decoded;
    } catch (\Firebase\JWT\ExpiredException $e) {
        // Handle expired token
    } catch (\Firebase\JWT\SignatureInvalidException $e) {
        // Handle invalid signature
    }
    
  3. Using JWK (JSON Web Key) for Asymmetric Signing

    $jwk = [
        'kty' => 'RSA',
        'e' => 'AQAB',
        'n' => 'your_modulus_here',
        'd' => 'your_private_exponent',
        'p' => 'your_first_factor',
        'q' => 'your_second_factor',
        'dp' => 'your_first_factor_crt',
        'dq' => 'your_second_factor_crt',
        'qi' => 'your_first_crt_coefficient'
    ];
    $token = JWT::encode($payload, $jwk, 'RS256');
    
  4. Middleware for Laravel Create a middleware to validate JWTs on protected routes:

    namespace App\Http\Middleware;
    
    use Closure;
    use Firebase\JWT\JWT;
    use Firebase\JWT\ExpiredException;
    
    class AuthenticateJWT
    {
        public function handle($request, Closure $next)
        {
            $token = $request->bearerToken();
            if (!$token) {
                return response()->json(['error' => 'Token not provided'], 401);
            }
    
            try {
                $decoded = JWT::decode($token, config('jwt.secret'), [config('jwt.algorithm')]);
                $request->merge(['user' => (array) $decoded]);
            } catch (ExpiredException $e) {
                return response()->json(['error' => 'Token expired'], 401);
            } catch (\Exception $e) {
                return response()->json(['error' => 'Invalid token'], 401);
            }
    
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $routeMiddleware = [
        'jwt.auth' => \App\Http\Middleware\AuthenticateJWT::class,
    ];
    
  5. Storing Tokens Securely Use Laravel's encrypt() for sensitive keys:

    $secret = config('jwt.secret');
    $encrypted = encrypt($secret); // Store this in DB/env
    

Gotchas and Tips

Pitfalls

  1. Algorithm Mismatch

    • If encoding with HS256 but decoding with RS256, the signature will fail.
    • Fix: Ensure the same algorithm is used for encoding/decoding.
  2. Clock Skew in Validation

    • Tokens with nbf (not before) or exp (expiry) claims may fail due to server time mismatches.
    • Fix: Configure a leeway (e.g., 5 minutes) in the decoder:
      $decoded = JWT::decode($token, 'secret', ['HS256'], true, ['leeway' => 300]);
      
  3. JWK Key Format

    • The library expects a specific JWK structure. Missing fields (e.g., d, p, q for RSA) will cause errors.
    • Fix: Validate JWK structure before use or use a library like web-token/jwt-framework for generation.
  4. Deprecated Methods

    • Avoid JWT::verify() in favor of JWT::decode() + exception handling (more explicit).
  5. No Built-in Refresh Tokens

    • The package doesn’t handle refresh tokens natively. Implement manually:
      if ($decoded->refresh_token && $request->input('refresh_token') === $decoded->refresh_token) {
          $newToken = JWT::encode($payload, 'secret', 'HS256');
          return response()->json(['token' => $newToken]);
      }
      

Debugging Tips

  1. Decode Without Validation Use JWT::decode($token, null, ['HS256']) to inspect payloads without signature checks.

  2. Check Token Structure Use jwt.io to validate token claims manually.

  3. Enable Error Logging Wrap decodes in try-catch blocks to log exceptions:

    try {
        $decoded = JWT::decode($token, 'secret', ['HS256']);
    } catch (\Exception $e) {
        \Log::error("JWT Decode Error: " . $e->getMessage());
        throw $e;
    }
    

Extension Points

  1. Custom Claims Validation Extend the library by adding a validator:

    class CustomJWTValidator
    {
        public static function validate($payload)
        {
            if (!isset($payload->iss) || $payload->iss !== 'your-app') {
                throw new \Exception('Invalid issuer');
            }
        }
    }
    

    Use in middleware:

    CustomJWTValidator::validate($decoded);
    
  2. Key Management For production, integrate with a key management system (e.g., AWS KMS, HashiCorp Vault) to fetch JWKs dynamically.

  3. Performance

    • Cache decoded tokens if they’re reused (e.g., in a session).
    • Avoid decoding the same token multiple times in a request.
  4. Testing Use JWT::encode() with predictable payloads/secrets for unit tests:

    $testToken = JWT::encode(['test' => true], 'secret', 'HS256');
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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