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

vonage/jwt

PHP 8.1+ library to generate JWTs for authenticating with Vonage APIs. Install via Composer, create a TokenGenerator with your Vonage Application ID and private key, then call generate() to get a bearer token for requests.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require vonage/jwt
    

    No additional configuration is required—this is a standalone library.

  2. First Use Case: Generating a JWT for Vonage APIs

    use Vonage\JWT\JWT;
    
    $jwt = new JWT();
    $token = $jwt->generate([
        'iss' => 'your-app-id', // Vonage API issuer (your app ID)
        'sub' => 'user-123',   // Subject (e.g., user ID or endpoint)
        'iat' => time(),       // Issued at (timestamp)
        'exp' => time() + 3600,// Expiration (1 hour later)
        'aud' => 'vonage',     // Audience (Vonage APIs)
        'jti' => bin2hex(random_bytes(16)) // Unique token ID
    ], 'your-secret-key'); // Your Vonage API secret key
    
  3. Where to Look First

    • Documentation: Vonage JWT API Docs (official guide for payload structure).
    • Source: JWT.php (minimal class with no external dependencies).
    • Tests: tests/ for edge cases (e.g., invalid keys, expired tokens).

Implementation Patterns

Core Workflow: JWT Generation

  1. Payload Structure Vonage APIs enforce specific claims. Use this template:

    $payload = [
        'iss' => env('VONAGE_APP_ID'), // Required by Vonage
        'sub' => $user->id,            // Customizable (e.g., user ID or endpoint)
        'iat' => time(),
        'exp' => time() + 300,         // Short-lived tokens (5 mins) for security
        'aud' => 'vonage',
        'jti' => Str::uuid()->toString(),
        'scope' => ['sms:send', 'verify:start'], // Permissions (API-specific)
    ];
    
    • Tip: Store VONAGE_APP_ID and VONAGE_API_SECRET in .env.
  2. Token Rotation Generate new tokens for each request to Vonage APIs (avoid long-lived tokens):

    $token = $jwt->generate($payload, env('VONAGE_API_SECRET'));
    $client->setAuth($token); // Integrate with Vonage SDK (e.g., `vonage/client`)
    
  3. Validation (Optional) Verify tokens before use (e.g., in middleware):

    use Vonage\JWT\JWT;
    
    $jwt = new JWT();
    $isValid = $jwt->verify($token, env('VONAGE_API_SECRET'));
    

Integration with Laravel

  1. Service Provider Bind the JWT class for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(JWT::class, fn() => new JWT());
    }
    
  2. API Requests Use the token in Vonage SDK calls:

    $client = new \Vonage\Client\Credentials\Basic(
        env('VONAGE_API_KEY'),
        env('VONAGE_API_SECRET')
    );
    $client->setAuth($jwt->generate($payload, env('VONAGE_API_SECRET')));
    
  3. Caching Tokens (Advanced) Cache tokens for 1 minute to reduce generation overhead:

    $token = Cache::remember('vonage_jwt_token', 60, function () {
        return $jwt->generate($payload, env('VONAGE_API_SECRET'));
    });
    

Gotchas and Tips

Pitfalls

  1. Secret Key Management

    • Gotcha: Hardcoding secrets in code. Always use .env.
    • Fix: Use Laravel’s env() or config() helper:
      $secret = config('services.vonage.secret');
      
  2. Token Expiration

    • Gotcha: Vonage APIs may reject tokens with exp > 24 hours.
    • Fix: Set exp to time() + 3600 (1 hour) or shorter.
  3. Payload Validation

    • Gotcha: Missing required claims (iss, aud, sub) will fail silently in some Vonage APIs.
    • Fix: Validate payload before generation:
      $required = ['iss', 'sub', 'iat', 'exp', 'aud', 'jti'];
      foreach ($required as $claim) {
          if (!array_key_exists($claim, $payload)) {
              throw new \InvalidArgumentException("Missing claim: {$claim}");
          }
      }
      
  4. Clock Skew

    • Gotcha: Server time mismatches can cause exp validation failures.
    • Fix: Use NTP-synchronized servers or add a 5-minute buffer to exp.

Debugging

  1. Decode Tokens Locally Use jwt.io to debug payloads/headers. For PHP:

    $decoded = (array) JWT::decode($token, env('VONAGE_API_SECRET'), ['HS256']);
    
  2. Vonage API Errors

    • 401 Unauthorized: Invalid token or secret.
    • 403 Forbidden: Missing/invalid scope claims.
    • Fix: Check Vonage’s API error docs.

Extension Points

  1. Custom Claims Add API-specific claims (e.g., application_id for Vonage Verify):

    $payload['application_id'] = env('VONAGE_APPLICATION_ID');
    
  2. Algorithm Support The package defaults to HS256. For RS256 (public/private keys):

    $jwt->generate($payload, ['private_key' => file_get_contents('path/to/key.pem'), 'algorithm' => 'RS256']);
    
  3. Testing Mock the JWT class in tests:

    $mockJWT = Mockery::mock(JWT::class);
    $mockJWT->shouldReceive('generate')->andReturn('mock-token');
    $this->app->instance(JWT::class, $mockJWT);
    

Performance

  • Avoid Regeneration: Cache tokens for short-lived operations (e.g., webhooks).
  • Key Size: Use 256-bit or 512-bit secrets for HS256/HS512 (avoid weak keys).
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