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

nixilla/php-jwt

Lightweight PHP JWT library for creating and validating JSON Web Tokens. Sign and verify tokens with common algorithms, manage claims (exp/iat/nbf), and handle key/secret configuration. Suitable for simple auth and API token workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require nixilla/php-jwt
    

    Ensure your PHP version is 7.2+ (check composer.json for compatibility).

  2. First Use Case: Signing a JWT

    use Nixilla\JWT\JWT;
    
    $jwt = new JWT();
    $secretKey = 'your-256-bit-secret'; // Must be at least 32 chars for HS256
    $payload = [
        'iss' => 'your-app',
        'iat' => time(),
        'data' => ['user_id' => 123]
    ];
    
    $token = $jwt->encode($payload, $secretKey);
    // Output: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
    
  3. Decoding a JWT

    $decoded = $jwt->decode($token, $secretKey, ['HS256']);
    // Returns array of payload data
    
  4. Verify Token Existence

    if ($jwt->verify($token, $secretKey, ['HS256'])) {
        // Token is valid
    }
    

Where to Look First

  • Documentation: Check the GitHub repo (if available) or inline PHPDoc comments in src/Nixilla/JWT/JWT.php.
  • Examples: Look for tests/ directory for usage patterns (e.g., JWTTest.php).
  • Config: No external config file; all settings are passed via method arguments.

Implementation Patterns

Common Workflows

  1. API Authentication Middleware

    // app/Http/Middleware/VerifyJWT.php
    public function handle($request, Closure $next) {
        $token = $request->bearerToken();
        $jwt = new JWT();
        $decoded = $jwt->decode($token, config('jwt.secret'), ['HS256']);
    
        if (!$decoded) {
            return response()->json(['error' => 'Invalid token'], 401);
        }
        $request->merge(['user' => $decoded['data']]);
        return $next($request);
    }
    
  2. Token Generation Service

    // app/Services/JWTService.php
    class JWTService {
        public function generateToken(array $payload): string {
            $jwt = new JWT();
            return $jwt->encode($payload, config('jwt.secret'), 'HS256', 3600); // 1-hour expiry
        }
    }
    
  3. Refresh Tokens

    $refreshToken = $jwt->encode([
        'iss' => 'refresh',
        'iat' => time(),
        'exp' => time() + (86400 * 7) // 7 days
    ], $secretKey, 'HS256');
    

Integration Tips

  • Laravel Config: Store secrets in .env:
    JWT_SECRET=your-32-char-secret-here
    JWT_ALGORITHM=HS256
    
  • Dependency Injection: Bind the JWT class in AppServiceProvider:
    $this->app->singleton(JWT::class, function () {
        return new JWT();
    });
    
  • Error Handling: Wrap JWT operations in try-catch:
    try {
        $decoded = $jwt->decode($token, $secretKey);
    } catch (\Exception $e) {
        Log::error("JWT decode failed: " . $e->getMessage());
        return response()->json(['error' => 'Invalid token'], 401);
    }
    

Gotchas and Tips

Pitfalls

  1. Secret Key Length

    • Issue: Using a key shorter than 32 chars for HS256 (or 512 bits for RS256).
    • Fix: Ensure keys meet algorithm requirements (e.g., 32+ chars for HS256).
    • Debug: Invalid key length or Invalid signature errors.
  2. Algorithm Mismatch

    • Issue: Decoding a token signed with HS256 using RS256 (or vice versa).
    • Fix: Always pass the correct algorithm to decode()/verify():
      $jwt->decode($token, $secretKey, ['HS256']); // Explicit algorithm
      
  3. Clock Skew

    • Issue: Tokens rejected due to server time mismatches (e.g., exp claim).
    • Fix: Use leeway in decode():
      $jwt->decode($token, $secretKey, [], 300); // 5-minute leeway
      
  4. No Built-in Storage

    • Issue: The package doesn’t handle token storage/revocation.
    • Fix: Use Laravel’s cache or a database table (e.g., revoked_tokens).

Debugging Tips

  • Validate Payloads: Use JWT::isValid() for quick checks:
    if (!$jwt->isValid($token, $secretKey, ['HS256'])) {
        // Handle invalid token
    }
    
  • Inspect Tokens: Decode manually to debug:
    composer require firebase/php-jwt
    php -r '$token="..."; $decoded = (new \Firebase\JWT\JWT())->decode($token); print_r($decoded);'
    
  • Log Errors: Enable Laravel’s debug mode and log exceptions:
    try {
        $jwt->decode($token, $secretKey);
    } catch (\Exception $e) {
        Log::debug("JWT Error: " . $e->getMessage());
    }
    

Extension Points

  1. Custom Claims Add non-standard claims (e.g., jti for idempotency):

    $payload = [
        'jti' => Str::uuid()->toString(),
        'data' => [...]
    ];
    
  2. Algorithm Switching Dynamically switch algorithms (e.g., for testing):

    $algorithm = config('jwt.algorithm', 'HS256');
    $jwt->decode($token, $secretKey, [$algorithm]);
    
  3. Event Hooks Extend the JWT class to add pre/post hooks:

    class CustomJWT extends JWT {
        public function encode($payload, $secret, $alg = 'HS256', $exp = 0) {
            $this->logPayload($payload); // Custom logic
            return parent::encode($payload, $secret, $alg, $exp);
        }
    }
    
  4. Testing Mock the JWT class in PHPUnit:

    $mockJWT = $this->createMock(JWT::class);
    $mockJWT->method('decode')->willReturn(['data' => ['user_id' => 1]]);
    $this->app->instance(JWT::class, $mockJWT);
    
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.
terminal42/code-quality-tools
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