Skip to content

Getting Started

← Back to index


Requirements

  • PHP 8.2 or higher
  • CodeIgniter 4.x
  • Composer

Installation

composer require daycry/jwt

Initial Setup

1. Publish the configuration file

php spark jwt:publish

This copies the default config into your application at app/Config/JWT.php.

2. Generate a secure signing key

php spark jwt:key

The key is written automatically to your .env file as jwt.signer. Alternatively, display it without writing to disk:

php spark jwt:key --show

3. Verify the .env entry

jwt.signer = "<paste-the-key-generated-above-here>"

⚠️ The library refuses to encode or decode tokens until jwt.signer is set to a non-empty base64 string. Never commit your signing key to version control. Add .env to .gitignore.


Quick Example

<?php

use Daycry\JWT\JWT;

// --- Encoding ---
$jwt   = JWT::for();                     // falls back to config('JWT')
$token = $jwt->encode('hello world');    // scalar payload
// A uid may be a string or an integer ID (e.g. a DB primary key);
// the JSON type is preserved, so an integer uid round-trips as an integer.
// $token = $jwt->encode(['user_id' => 1, 'role' => 'admin'], 42);

// --- Decoding ---
$token0 = $jwt->decode($token);              // returns a Lcobucci\JWT\Token\Plain

echo $token0->claims()->get('data');         // "hello world"
echo $token0->claims()->get('uid');          // value from config or second encode() argument

// Or read the original payload directly (auto-decodes compact JSON):
echo $jwt->getPayload($token);               // "hello world"

Dependency Injection

You can inject a custom config object instead of relying on config('JWT'):

use Daycry\JWT\JWT;
use Daycry\JWT\Config\JWT as JWTConfig;

$config            = new JWTConfig();
$config->issuer    = 'https://my-app.com';
$config->expiresAt = '+1 hour';

$jwt = new JWT($config);

This pattern is especially useful in tests and service containers.


Next Steps

Topic Document
All configuration options Configuration
encode / decode / validate Usage
CLI commands reference CLI Commands
Utility methods & error handling Advanced
Running the test suite Testing