1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
| use ErikJwt\Config; use ErikJwt\JWTFactory; use ErikJwt\JWTException;
try { $jwt = JWTFactory::createFromConfig(); $token = $jwt->encode(['user_id' => 123, 'username' => 'testuser']); echo "Token generated: " . substr($token, 0, 50) . "...\n";
$refreshToken = $jwt->encode([ 'user_id' => 123, 'token_type' => 'refresh' ], 86400);
$payload = $jwt->decode($token); echo "Token validated for user: " . $payload['username'] . "\n"; $jwt->validate($token);
$jwt->blacklist($token); echo "Token blacklisted\n"; if ($jwt->isBlacklisted($token)) { echo "Token correctly identified as blacklisted\n"; } } catch (JWTException $e) { switch ($e->getCode()) { case JWTException::STORAGE_ERROR: echo "Storage error: " . $e->getMessage() . "\n"; $fallbackConfig = new Config([ 'secret_key' => 'your-secret-key', 'storage' => ['type' => 'file'] ]); $jwt = JWTFactory::createFromConfig($fallbackConfig); echo "Fallback to file storage\n"; break; case JWTException::NETWORK_ERROR: echo "Network error: " . $e->getMessage() . "\n"; break; case JWTException::CONFIG_ERROR: echo "Configuration error: " . $e->getMessage() . "\n"; break; default: echo "JWT error: " . $e->getMessage() . "\n"; break; } } catch (Exception $e) { echo "Unexpected error: " . $e->getMessage() . "\n"; }
function createJWTWithFallback(array $configs): \ErikJwt\JWT { $lastException = null; foreach ($configs as $config) { try { return JWTFactory::createFromConfig(new \ErikJwt\Config($config)); } catch (JWTException $e) { $lastException = $e; continue; } } throw $lastException; }
$configs = [ [ 'secret_key' => 'your-secret-key', 'storage' => [ 'type' => 'redis', 'config' => [ 'database' => 1, 'prefix' => 'prod:jwt:blacklist:', 'timeout' => 1.0, 'read_timeout' => 1.0, 'persistent' => true, 'persistent_id' => 'jwt_pool' ] ] ], [ 'secret_key' => 'your-secret-key', 'storage' => [ 'type' => 'database', 'config' => [ 'table_name' => 'user_token_blacklist', ] ] ], [ 'secret_key' => 'your-secret-key', 'storage' => ['type' => 'file'] ] ];
try { $jwt = createJWTWithFallback($configs); echo "JWT instance created successfully with fallback\n"; } catch (Exception $e) { echo "All storage backends failed: " . $e->getMessage() . "\n"; }
|