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

Jwt Framework Laravel Package

web-token/jwt-framework

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require web-token/jwt-framework

For Symfony projects, use the bundle:

composer require web-token/jwt-framework-bundle
  1. First Use Case: Generate and verify a JWT token in a Laravel controller:

    use WebToken\JWT\Builder;
    use WebToken\JWT\Signature\Algorithm\HS256;
    use WebToken\JWT\Signature\Key\InMemory;
    
    // Create a key (store securely in production)
    $key = new InMemory('your-secret-key');
    
    // Build and sign a token
    $builder = new Builder();
    $token = $builder
        ->withPayload(['user_id' => 123, 'role' => 'admin'])
        ->withKey($key, new HS256())
        ->getToken();
    
    // Verify and decode the token
    $verifier = new Verifier($key, new HS256());
    $decoded = $verifier->verify($token);
    
  2. Where to Look First:

    • Official Documentation (API reference, usage guides)
    • src/WebToken/JWT/ directory for core classes
    • tests/ for practical examples and edge cases

Implementation Patterns

Core Workflows

1. Token Generation

  • Builder Pattern: Chain methods for payload, claims, and signing:
    $token = (new Builder())
        ->withPayload(['sub' => 'user123'])
        ->issuedAt(time())
        ->expiresAt(time() + 3600)
        ->withKey($key, new RS256())
        ->getToken();
    
  • Custom Claims: Extend AbstractClaim or use CustomClaim:
    $claim = new CustomClaim('custom_claim', 'value');
    $builder->withClaim($claim);
    

2. Token Verification

  • Verifier Class: Centralized validation with checkers:
    $verifier = new Verifier($key, new ES256());
    $decoded = $verifier->verify($token, [
        new ExpirationTimeChecker($clock),
        new IssuedAtChecker($clock),
    ]);
    
  • Custom Checkers: Implement CheckerInterface for business logic:
    class RoleChecker implements CheckerInterface {
        public function check(JWT $jwt): void {
            if ($jwt->getPayload()['role'] !== 'admin') {
                throw new \RuntimeException('Invalid role');
            }
        }
    }
    

3. Key Management

  • Key Storage: Use KeyStorageInterface (e.g., FileKeyStorage, RedisKeyStorage):
    $storage = new FileKeyStorage('/path/to/keys');
    $key = $storage->getKey('my-key-id');
    
  • Key Rotation: Implement KeyRotationStrategy for automated key updates.

4. Encrypted Tokens (JWE)

  • Encryption Workflow:
    $jweBuilder = new JWEBuilder();
    $encrypted = $jweBuilder
        ->withPlaintext('sensitive-data')
        ->withKeyEncryptionKey($keyEncryptionKey, new A256KW())
        ->withContentEncryptionKey($contentKey, new A256GCM())
        ->getToken();
    
    $jweDecrypter = new JWEDecrypter();
    $plaintext = $jweDecrypter
        ->withToken($encrypted)
        ->withKeyDecryptionKey($keyEncryptionKey, new A256KW())
        ->withContentDecryptionKey($contentKey, new A256GCM())
        ->getPlaintext();
    

5. Integration with Laravel

  • Middleware for API Protection:
    namespace App\Http\Middleware;
    
    use Closure;
    use WebToken\JWT\Verification\Verifier;
    
    class AuthenticateJWT {
        public function handle($request, Closure $next) {
            $token = $request->bearerToken();
            $verifier = app(Verifier::class);
            $decoded = $verifier->verify($token);
            auth()->setUser($decoded->getPayload());
            return $next($request);
        }
    }
    
  • Service Provider Setup:
    public function register() {
        $this->app->singleton(Verifier::class, function ($app) {
            $key = new InMemory(config('jwt.secret'));
            return new Verifier($key, new HS256());
        });
    }
    

6. Testing

  • Mocking Keys:
    $mockKey = $this->createMock(InMemory::class);
    $mockKey->method('getKeyMaterial')->willReturn('mock-key');
    $verifier = new Verifier($mockKey, new HS256());
    
  • Assertions:
    $this->expectException(JWTException::class);
    $verifier->verify('invalid.token');
    

Advanced Patterns

1. Algorithm Agility

  • Dynamic Algorithm Selection:
    $alg = $request->input('alg', 'HS256');
    $algorithm = match ($alg) {
        'RS256' => new RS256(),
        'ES256' => new ES256(),
        default => new HS256(),
    };
    

2. Token Refresh

  • Refresh Token Flow:
    $refreshToken = $builder
        ->withPayload(['jti' => 'refresh-123'])
        ->withKey($refreshKey, new HS512())
        ->issuedAt(time())
        ->expiresAt(time() + 86400) // 24h expiry
        ->getToken();
    
    // Validate refresh token and issue new access token
    $verifier->verify($refreshToken);
    $accessToken = $builder
        ->withPayload(['sub' => 'user123'])
        ->withKey($accessKey, new HS256())
        ->getToken();
    

3. Custom Headers

  • Non-Standard Headers:
    $builder->withHeader('custom_header', 'value');
    $decoded = $verifier->verify($token);
    $customHeader = $decoded->getHeader('custom_header');
    

4. Performance Optimization

  • Caching Keys:
    $cache = new Psr6CacheAdapter(new FilesystemCacheStorage('/path/to/cache'));
    $storage = new CachedKeyStorage($fileStorage, $cache);
    
  • Sodium Acceleration (if available):
    if (extension_loaded('sodium')) {
        Base64UrlSafe::setSodiumSupport(true);
    }
    

Gotchas and Tips

Common Pitfalls

1. Algorithm Mismatch

  • Issue: Using HS256 for signing but verifying with RS256.
  • Fix: Ensure the same algorithm is used for both signing and verification.
  • Debugging:
    try {
        $verifier->verify($token);
    } catch (JWTException $e) {
        if ($e->getCode() === JWTException::INVALID_ALGORITHM) {
            // Handle algorithm mismatch
        }
    }
    

2. Key Management

  • Issue: Hardcoding keys in source code.
  • Fix: Use environment variables or secure storage:
    $key = new InMemory(config('jwt.secret'));
    
  • Tip: Rotate keys periodically and use KeyRotationStrategy.

3. Time Skew

  • Issue: Clock desynchronization between services.
  • Fix: Use PSR-20 ClockInterface and allow a small leeway:
    $clock = new SystemClock();
    $checker = new ExpirationTimeChecker($clock, 60); // 1-minute leeway
    

4. Payload Size

  • Issue: JWTs exceeding URL/HTTP limits (~4KB).
  • Fix: Use JWE for large payloads or split data into multiple tokens.

5. Algorithm Confusion

  • Issue: Attackers manipulating the alg header.
  • Fix: Use JWS with integrity-protected headers (enabled by default in v4.1+).

6. Base64URL Encoding

  • Issue: Incorrect encoding/decoding of tokens.
  • Fix: Always use Base64UrlSafe utilities:
    use WebToken\Base64UrlSafe\Base64UrlSafe;
    $decoded = Base64UrlSafe::decode($token);
    

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