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

lcobucci/jwt

A lightweight, flexible JWT library for PHP. Create, sign, parse, and validate JSON Web Tokens with support for multiple algorithms, key types, constraints, and claims. Includes a fluent builder, token parser, and robust validation APIs.

View on GitHub
Deep Wiki
Context7

Getting Started

Begin by installing via Composer: composer require lcobucci/jwt. The core workflow involves three steps: building tokens with Builder, signing them with a Signer (e.g., Hmac\Sha256 or Signer\RSA\Sha256), and validating using ValidationData and Constraints. For Laravel, integrate using a service provider or direct usage in auth-related services. Start by generating a minimal token:

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Token\Parsed;

$signer = new Sha256();
$key = 'your-secret-key';

$token = (new Builder())
    ->setIssuer('your-app')
    ->setAudience('your-client')
    ->setId('token-id-123', true)
    ->setIssuedAt(time())
    ->setExpiration(time() + 3600)
    ->set('uid', 42)
    ->sign($signer, $key)
    ->toString();

Parse and validate next:

use Lcobucci\JWT\Parser;
use Lcobucci\JWT\ValidationData;

$parser = new Parser();
$token = $parser->parse($tokenString);

// Validate standard claims (exp, iat, etc.) via ValidationData
$data = new ValidationData();
$data->setIssuer('your-app');
$data->setAudience('your-client');
$data->setId('token-id-123');

if ($token->validate($data)) {
    // Validate against signer too
    if ($token->verify($signer, $key)) {
        $uid = $token->claims()->get('uid');
    }
}

Implementation Patterns

  • Token Issuer Service: Create a dedicated TokenIssuer class to centralize signing logic and key management. Inject Signer and configuration (keys, TTL).
  • Validation Constraints: For complex rules, use lcobucci/jwt’s Constraints (e.g., AllowedAudience, IssuedBy, SameDomainIssuedBy, NotBefore) with $token->assert($constraints) — more modern and composable than ValidationData.
  • RSA/ECDSA in Production: Prefer asymmetric keys for security. Use environment variables or Vault for private key paths; store public keys in config. Load keys via new Key('file:///path/to/key.pem').
  • Laravel Integration: Extend JWTAuthService with Builder/Parser usage. Use Token Retrieved events to hydrate user context. Store tokens in cache for revocation (use jti claim).
  • Custom Claims: Define enums or constants for claim keys (e.g., RoleClaim::value) to prevent typos and improve maintainability.
  • Debugging Endpoints: Use a dev route to generate test tokens for local testing (only in dev!).

Gotchas and Tips

  • Strict Validation: validate() only checks time-based and standard claims (exp, iat, nbf, iss, aud, jti). For issuer/audience, use ValidationData or pass constraints to assert().
  • Signer Interface Changes: In v4+, Signer instances are stateless and immutable; verify() and sign() accept both key strings or Key objects. Prefer Key for file-based keys to avoid accidental truncation.
  • Time Zone Pitfalls: Always use UTC timestamps (via time() or Carbon::now()->timestamp). Avoid mktime() or strtotime() without explicit timezone.
  • Revocation Limitations: JWTs are stateless; revocation requires external tracking (e.g., jti + Redis TTL or DB). Store jti + revoked timestamp on logout.
  • Error Handling: Parser throws UnexpectedValueException on parse failures. Wrap parsing in try-catch and map to user-friendly messages. validate() and verify() return bool.
  • Extensibility: Override claim types via custom Claim subclasses, but prefer built-in ones unless absolutely necessary. Builder accepts Claim objects for advanced claims (e.g., NonEmptyArrayClaim).
  • Security Reminder: Never log raw tokens or keys. Use rate limiting on token generation/revocation endpoints. Prefer short TTLs + refresh tokens.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport