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

web-token/jwt-checker

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require web-token/jwt-checker
    

    Add to composer.json if using a custom package:

    "require": {
        "web-token/jwt-checker": "^1.0"
    }
    
  2. Basic Usage

    use WebToken\JWTChecker\Checker;
    
    $checker = new Checker();
    $isValid = $checker->check($jwtString);
    
  3. First Use Case Validate a JWT in a Laravel middleware:

    use WebToken\JWTChecker\Checker;
    
    class AuthenticateJWT
    {
        public function handle($request, Closure $next)
        {
            $checker = new Checker();
            $token = $request->bearerToken();
    
            if (!$token || !$checker->check($token)) {
                return response()->json(['error' => 'Invalid token'], 401);
            }
    
            return $next($request);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Token Validation in Controllers

    public function protectedRoute(Request $request)
    {
        $checker = new Checker();
        $token = $request->header('Authorization') ?? '';
    
        if (!$checker->check($token)) {
            abort(401, 'Unauthorized');
        }
    
        // Proceed with logic
    }
    
  2. Integration with Laravel Auth Override Laravel’s AuthenticatesUsers trait to use JWT:

    use WebToken\JWTChecker\Checker;
    
    public function attemptLogin(Request $request)
    {
        $checker = new Checker();
        $token = $request->input('token');
    
        if ($checker->check($token)) {
            $user = $this->getUserFromToken($token); // Custom logic
            return $this->authenticate($user);
        }
    
        return false;
    }
    
  3. Custom Claims Validation Extend the checker for domain-specific rules:

    $checker = new Checker();
    $claims = $checker->getClaims($jwtString);
    
    if ($claims['role'] !== 'admin') {
        abort(403, 'Forbidden');
    }
    

Advanced Patterns

  • Token Refresh Logic

    $checker = new Checker();
    if ($checker->isExpired($jwtString)) {
        $newToken = $this->refreshToken($user); // Custom refresh logic
        return response()->json(['token' => $newToken]);
    }
    
  • Batch Validation

    $tokens = ['token1', 'token2'];
    $validTokens = array_filter($tokens, fn($token) => $checker->check($token));
    

Gotchas and Tips

Common Pitfalls

  1. Token Format Assumptions The package expects a compact JWT string (e.g., eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...). Fix: Decode base64 if the token is URL-safe:

    $jwtString = strtr(base64_decode($token), '+/', '-_');
    
  2. Time Zone Sensitivity The checker uses the system’s default time zone. For consistency:

    $checker = new Checker();
    $checker->setTimeZone('UTC'); // Explicitly set
    
  3. Silent Failures check() returns false for any invalid token (malformed, expired, etc.). Debugging: Use getClaims() to inspect errors:

    try {
        $claims = $checker->getClaims($jwtString);
    } catch (\Exception $e) {
        // Log or handle specific errors (e.g., expired, invalid signature)
    }
    

Extension Points

  1. Custom Algorithms Override the default HS256/RS256 validation:

    $checker = new Checker();
    $checker->setAlgorithm('ES256'); // Elliptic Curve
    
  2. Claim-Specific Validation Add pre-check logic:

    $claims = $checker->getClaims($jwtString);
    if ($claims['exp'] < time() - 3600) { // Hard block old tokens
        throw new \RuntimeException('Token too old');
    }
    
  3. Performance

    • Cache the Checker instance (stateless but avoids re-parsing).
    • For high-throughput APIs, validate tokens before routing (e.g., in a sub-request middleware).

Debugging Tips

  • Inspect Raw Claims
    $checker->getClaims($jwtString); // Returns decoded payload
    
  • Enable Verbose Errors
    $checker->setVerbose(true); // Logs detailed validation steps
    
  • Test with Known Tokens Use jwt.io to generate/test tokens offline.

Laravel-Specific Quirks

  • Service Container Binding Bind the checker in AppServiceProvider:
    $this->app->singleton(Checker::class, fn() => new Checker());
    
    Then inject via constructor:
    public function __construct(private Checker $checker) {}
    
  • Caching Tokens Store validated claims in the session/cache to avoid re-parsing:
    $cacheKey = 'jwt_'.$token;
    if (!$claims = cache()->get($cacheKey)) {
        $claims = $checker->getClaims($token);
        cache()->put($cacheKey, $claims, now()->addMinutes(5));
    }
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle