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

dorcyv/jwt-session-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run composer require dorcyv/jwt-session-bundle in your Laravel project root. (Note: While the package is Symfony-focused, Laravel can leverage its core logic via a custom session driver or middleware.)

  2. Configuration Override Laravel’s default session driver in config/session.php:

    'driver' => 'jwt', // Custom driver (see Implementation Patterns)
    

    (The bundle itself doesn’t natively integrate with Laravel, so you’ll need to adapt it—see next section.)

  3. First Use Case Test a JWT-based session by:

    • Setting a session variable: session(['jwt_test' => 'value']).
    • Verifying persistence across requests (no server-side storage).
    • Checking the X-JWT-Session cookie (or equivalent) in browser dev tools.

Implementation Patterns

Laravel Integration Workflow

  1. Create a Custom Session Driver Extend Laravel’s SessionManager to use the bundle’s JwtSessionHandler:

    // app/Providers/AppServiceProvider.php
    use Dorcyv\JwtSessionBundle\Session\JwtSessionHandler;
    
    public function register()
    {
        $this->app->extend('session', function ($app) {
            $handler = new JwtSessionHandler(
                $app['config']['jwt_session.key'],
                $app['config']['jwt_session.ttl']
            );
            return new \Illuminate\Session\Store(
                $handler,
                new \Illuminate\Session\Middleware\StartSession()
            );
        });
    }
    
  2. Configure JWT Settings Add to config/session.php:

    'jwt_session' => [
        'key' => env('JWT_SECRET', 'your-256-bit-secret'),
        'ttl' => 3600, // Token lifetime (seconds)
        'algorithm' => 'HS256', // Default algorithm
    ],
    
  3. Middleware for JWT Validation Protect routes with a middleware to validate the JWT cookie:

    // app/Http/Middleware/ValidateJwtSession.php
    public function handle($request, Closure $next)
    {
        $jwt = $request->cookie('X-JWT-Session');
        if (!$jwt || !JwtSessionHandler::validate($jwt)) {
            abort(403, 'Invalid session');
        }
        return $next($request);
    }
    
  4. Fallback for Legacy Sessions Use a hybrid approach with a session() helper that falls back to file storage if JWT fails:

    if (!session()->has('jwt_fallback')) {
        session(['jwt_fallback' => true]);
    }
    

Key Patterns

  • Stateless Sessions: No server-side storage; rely on client-side cookies.
  • Token Rotation: Manually refresh tokens via API endpoints (e.g., /refresh-jwt).
  • Data Sensitivity: Avoid storing PII or sensitive data in the JWT payload (use encrypted session storage instead).

Gotchas and Tips

Pitfalls

  1. Cookie Size Limits

    • JWT tokens can grow large if session data is extensive. Browsers enforce ~4KB cookie limits.
    • Fix: Compress session data or use compact serialization.
  2. CSRF Vulnerabilities

    • JWT in cookies is vulnerable to CSRF if not paired with SameSite attributes.
    • Fix: Set SameSite=Strict and use Laravel’s csrf_token() middleware.
  3. Token Revocation

    • The bundle lacks built-in token revocation. Implement a short TTL (e.g., 15–30 mins) and require re-authentication.
    • Workaround: Store token hashes in a database for blacklisting (trade-off: server-side storage).
  4. Algorithm Mismatches

    • Ensure the algorithm in config/session.php matches the key length (e.g., HS256 requires a 32-byte/256-bit key).
    • Debug: Use openssl random -base64 32 to generate a secure key.
  5. Laravel Cache Integration

    • The bundle doesn’t support Laravel’s cache drivers. For hybrid setups, use cache()->remember() for non-JWT data.

Debugging Tips

  • Validate Tokens Manually:
    use Firebase\JWT\JWT;
    $decoded = JWT::decode($jwt, env('JWT_SECRET'), ['HS256']);
    
  • Check Cookie Headers: Use dd($request->headers()) to inspect the X-JWT-Session cookie.
  • Log Session Data: Add a middleware to log session payloads during development:
    public function handle($request, Closure $next)
    {
        \Log::debug('JWT Session Payload:', [
            'token' => $request->cookie('X-JWT-Session'),
            'data' => session()->all()
        ]);
        return $next($request);
    }
    

Extension Points

  1. Custom Claims Extend the JwtSessionHandler to add custom claims (e.g., user roles):

    $handler = new JwtSessionHandler($key, $ttl, [
        'iss' => 'your-app',
        'roles' => ['admin'] // Custom claim
    ]);
    
  2. Encrypted Payloads Encrypt sensitive session data before storing in the JWT:

    use Dorcyv\JwtSessionBundle\Session\Encryptor;
    
    $encryptedData = Encryptor::encrypt(session('sensitive_data'));
    session(['encrypted_data' => $encryptedData]);
    
  3. Multi-Server Sync Use a shared Redis cache for token metadata (e.g., jwt:revoked:{token_hash}) to simulate revocation without full server-side sessions.

  4. Fallback Driver Create a JwtFallbackSessionHandler that switches to file or database if JWT validation fails:

    class JwtFallbackSessionHandler implements SessionHandlerInterface
    {
        protected $jwtHandler;
        protected $fallbackHandler;
    
        public function __construct()
        {
            $this->jwtHandler = new JwtSessionHandler(...);
            $this->fallbackHandler = new \Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler();
        }
    
        public function read($sid)
        {
            try {
                return $this->jwtHandler->read($sid);
            } catch (\Exception $e) {
                return $this->fallbackHandler->read($sid);
            }
        }
        // Implement other SessionHandlerInterface methods...
    }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware