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

atlance/jwt-core

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require atlance/jwt-core
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Atlance\JwtCore\JwtCoreServiceProvider::class,
    ],
    
  2. Publish Config

    php artisan vendor:publish --provider="Atlance\JwtCore\JwtCoreServiceProvider"
    

    Configure .env and config/jwt.php with:

    • secret_key (e.g., base64:your-secret-key)
    • algorithm (e.g., HS256)
    • issuer (e.g., your-app-name)
    • audience (optional, e.g., your-app-client)
  3. First Use Case: Generate a Token

    use Atlance\JwtCore\Facades\Jwt;
    
    $token = Jwt::generate([
        'user_id' => 1,
        'role'    => 'admin',
    ]);
    

    Verify the token:

    $payload = Jwt::verify($token);
    

Implementation Patterns

Workflows

  1. Authentication Middleware Use Jwt::verify() in middleware to validate tokens:

    public function handle($request, Closure $next) {
        try {
            $payload = Jwt::verify($request->bearerToken());
            auth()->setUser($payload['user_id']);
            return $next($request);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
    }
    
  2. Token Refresh Store a refresh_token in the DB and issue a new JWT on refresh:

    $newToken = Jwt::generate([
        'user_id' => 1,
        'exp'     => now()->addHours(1), // Short-lived access token
    ]);
    
  3. Custom Claims Extend payloads with metadata:

    $token = Jwt::generate([
        'user_id' => 1,
        'metadata' => [
            'preferences' => ['theme' => 'dark'],
        ],
    ]);
    

Integration Tips

  • Laravel Sanctum: Combine with Sanctum for session-based auth.
  • API Routes: Protect routes with auth:api middleware.
  • Logging: Log token generation/verification for auditing:
    \Log::info('JWT Generated', ['token' => $token, 'payload' => $payload]);
    

Gotchas and Tips

Pitfalls

  1. Secret Key Management

    • Never hardcode secrets. Use .env and restrict file permissions.
    • Rotate keys periodically (e.g., via config/jwt.php updates).
  2. Algorithm Mismatch

    • Ensure algorithm in config/jwt.php matches the key type (e.g., HS256 for HMAC).
  3. Clock Skew

    • Tokens may fail if server times differ. Use NTP synchronization.
  4. Payload Size Limits

    • JWTs have a ~4KB limit. Avoid large payloads; use DB references instead.

Debugging

  • Verify Token Manually Use jwt.io to decode tokens for debugging.
  • Enable Debug Mode
    Jwt::setDebug(true); // Logs payloads/errors
    

Extension Points

  1. Custom Claims Validation Override Jwt::verify() logic:

    Jwt::verify($token, function ($payload) {
        if ($payload['role'] !== 'admin') {
            throw new \Exception('Insufficient permissions');
        }
    });
    
  2. Token Storage Store tokens in sessions or database for revocation:

    // Revoke token
    Jwt::blacklist($token);
    
  3. Event Listeners Trigger events on token generation/verification:

    Jwt::onGenerated(function ($token, $payload) {
        event(new TokenGenerated($payload));
    });
    
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.
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
spatie/mailcoach-vapor