Home > Dev > Crypto > JWT (JSON Web Tokens)

JWT (JSON Web Tokens)

This code snippet demonstrates how to create and verify JSON Web Tokens for secure API authentication.

use \Firebase\JWT\JWT;

function create_jwt($payload, $secret_key) {
    $issuedAt = time();
    $expirationTime = $issuedAt + 3600;  // jwt valid for 1 hour from the issued time
    $payload['iat'] = $issuedAt;
    $payload['exp'] = $expirationTime;

    return JWT::encode($payload, $secret_key);
}

function verify_jwt($jwt, $secret_key) {
    try {
        $decoded = JWT::decode($jwt, $secret_key, array('HS256'));
        return (array) $decoded;
    } catch (Exception $e) {
        return false;
    }
}

// Usage example
require 'vendor/autoload.php';  // Ensure you have the Firebase JWT package installed

$secret_key = 'your-secret-key';
$payload = array(
    'user_id' => 123,
    'email' => 'user@example.com'
);

$jwt = create_jwt($payload, $secret_key);
echo "JWT: " . $jwt . "\n";

$decoded = verify_jwt($jwt, $secret_key);
echo "Decoded JWT: " . print_r($decoded, true) . "\n";
Back