| 1 |
 |
| 2 |
[](https://packagist.org/packages/firebase/php-jwt](https://packagist.org/packages/firebase/php-jwt](https://packagist.org/packages/firebase/php-jwt) |
| 3 |
[](https://packagist.org/packages/firebase/php-jwt](https://packagist.org/packages/firebase/php-jwt](https://packagist.org/packages/firebase/php-jwt) |
| 4 |
[](https://packagist.org/packages/firebase/php-jwt](https://packagist.org/packages/firebase/php-jwt](https://packagist.org/packages/firebase/php-jwt) |
| 5 |
|
| 6 |
PHP-JWT |
| 7 |
======= |
| 8 |
A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to [](https://tools.ietf.org/html/rfc7519RFC 7519](https://tools.ietf.org/html/rfc7519](https://tools.ietf.org/html/rfc7519). |
| 9 |
|
| 10 |
Installation |
| 11 |
------------ |
| 12 |
|
| 13 |
Use composer to manage your dependencies and download PHP-JWT: |
| 14 |
|
| 15 |
```bash |
| 16 |
composer require firebase/php-jwt |
| 17 |
``` |
| 18 |
|
| 19 |
Optionally, install the `paragonie/sodium_compat` package from composer if your |
| 20 |
php is < 7.2 or does not have libsodium installed: |
| 21 |
|
| 22 |
```bash |
| 23 |
composer require paragonie/sodium_compat |
| 24 |
``` |
| 25 |
|
| 26 |
Example |
| 27 |
------- |
| 28 |
```php |
| 29 |
use Firebase\JWT\JWT; |
| 30 |
use Firebase\JWT\Key; |
| 31 |
|
| 32 |
$key = 'example_key'; |
| 33 |
$payload = [ |
| 34 |
'iss' => 'http://example.org', |
| 35 |
'aud' => 'http://example.com', |
| 36 |
'iat' => 1356999524, |
| 37 |
'nbf' => 1357000000 |
| 38 |
]; |
| 39 |
|
| 40 |
/** |
| 41 |
* IMPORTANT: |
| 42 |
* You must specify supported algorithms for your application. See |
| 43 |
* https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40 |
| 44 |
* for a list of spec-compliant algorithms. |
| 45 |
*/ |
| 46 |
$jwt = JWT::encode($payload, $key, 'HS256'); |
| 47 |
$decoded = JWT::decode($jwt, new Key($key, 'HS256')); |
| 48 |
|
| 49 |
print_r($decoded); |
| 50 |
|
| 51 |
/* |
| 52 |
NOTE: This will now be an object instead of an associative array. To get |
| 53 |
an associative array, you will need to cast it as such: |
| 54 |
*/ |
| 55 |
|
| 56 |
$decoded_array = (array) $decoded; |
| 57 |
|
| 58 |
/** |
| 59 |
* You can add a leeway to account for when there is a clock skew times between |
| 60 |
* the signing and verifying servers. It is recommended that this leeway should |
| 61 |
* not be bigger than a few minutes. |
| 62 |
* |
| 63 |
* Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef |
| 64 |
*/ |
| 65 |
JWT::$leeway = 60; // $leeway in seconds |
| 66 |
$decoded = JWT::decode($jwt, new Key($key, 'HS256')); |
| 67 |
``` |
| 68 |
Example with RS256 (openssl) |
| 69 |
---------------------------- |
| 70 |
```php |
| 71 |
use Firebase\JWT\JWT; |
| 72 |
use Firebase\JWT\Key; |
| 73 |
|
| 74 |
$privateKey = <<<EOD |
| 75 |
-----BEGIN RSA PRIVATE KEY----- |
| 76 |
MIICXAIBAAKBgQC8kGa1pSjbSYZVebtTRBLxBz5H4i2p/llLCrEeQhta5kaQu/Rn |
| 77 |
vuER4W8oDH3+3iuIYW4VQAzyqFpwuzjkDI+17t5t0tyazyZ8JXw+KgXTxldMPEL9 |
| 78 |
5+qVhgXvwtihXC1c5oGbRlEDvDF6Sa53rcFVsYJ4ehde/zUxo6UvS7UrBQIDAQAB |
| 79 |
AoGAb/MXV46XxCFRxNuB8LyAtmLDgi/xRnTAlMHjSACddwkyKem8//8eZtw9fzxz |
| 80 |
bWZ/1/doQOuHBGYZU8aDzzj59FZ78dyzNFoF91hbvZKkg+6wGyd/LrGVEB+Xre0J |
| 81 |
Nil0GReM2AHDNZUYRv+HYJPIOrB0CRczLQsgFJ8K6aAD6F0CQQDzbpjYdx10qgK1 |
| 82 |
cP59UHiHjPZYC0loEsk7s+hUmT3QHerAQJMZWC11Qrn2N+ybwwNblDKv+s5qgMQ5 |
| 83 |
5tNoQ9IfAkEAxkyffU6ythpg/H0Ixe1I2rd0GbF05biIzO/i77Det3n4YsJVlDck |
| 84 |
ZkcvY3SK2iRIL4c9yY6hlIhs+K9wXTtGWwJBAO9Dskl48mO7woPR9uD22jDpNSwe |
| 85 |
k90OMepTjzSvlhjbfuPN1IdhqvSJTDychRwn1kIJ7LQZgQ8fVz9OCFZ/6qMCQGOb |
| 86 |
qaGwHmUK6xzpUbbacnYrIM6nLSkXgOAwv7XXCojvY614ILTK3iXiLBOxPu5Eu13k |
| 87 |
eUz9sHyD6vkgZzjtxXECQAkp4Xerf5TGfQXGXhxIX52yH+N2LtujCdkQZjXAsGdm |
| 88 |
B2zNzvrlgRmgBrklMTrMYgm1NPcW+bRLGcwgW2PTvNM= |
| 89 |
-----END RSA PRIVATE KEY----- |
| 90 |
EOD; |
| 91 |
|
| 92 |
$publicKey = <<<EOD |
| 93 |
-----BEGIN PUBLIC KEY----- |
| 94 |
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8kGa1pSjbSYZVebtTRBLxBz5H |
| 95 |
4i2p/llLCrEeQhta5kaQu/RnvuER4W8oDH3+3iuIYW4VQAzyqFpwuzjkDI+17t5t |
| 96 |
0tyazyZ8JXw+KgXTxldMPEL95+qVhgXvwtihXC1c5oGbRlEDvDF6Sa53rcFVsYJ4 |
| 97 |
ehde/zUxo6UvS7UrBQIDAQAB |
| 98 |
-----END PUBLIC KEY----- |
| 99 |
EOD; |
| 100 |
|
| 101 |
$payload = [ |
| 102 |
'iss' => 'example.org', |
| 103 |
'aud' => 'example.com', |
| 104 |
'iat' => 1356999524, |
| 105 |
'nbf' => 1357000000 |
| 106 |
]; |
| 107 |
|
| 108 |
$jwt = JWT::encode($payload, $privateKey, 'RS256'); |
| 109 |
echo "Encode:\n" . print_r($jwt, true) . "\n"; |
| 110 |
|
| 111 |
$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256')); |
| 112 |
|
| 113 |
/* |
| 114 |
NOTE: This will now be an object instead of an associative array. To get |
| 115 |
an associative array, you will need to cast it as such: |
| 116 |
*/ |
| 117 |
|
| 118 |
$decoded_array = (array) $decoded; |
| 119 |
echo "Decode:\n" . print_r($decoded_array, true) . "\n"; |
| 120 |
``` |
| 121 |
|
| 122 |
Example with a passphrase |
| 123 |
------------------------- |
| 124 |
|
| 125 |
```php |
| 126 |
use Firebase\JWT\JWT; |
| 127 |
use Firebase\JWT\Key; |
| 128 |
|
| 129 |
// Your passphrase |
| 130 |
$passphrase = '[YOUR_PASSPHRASE]'; |
| 131 |
|
| 132 |
// Your private key file with passphrase |
| 133 |
// Can be generated with "ssh-keygen -t rsa -m pem" |
| 134 |
$privateKeyFile = '/path/to/key-with-passphrase.pem'; |
| 135 |
|
| 136 |
// Create a private key of type "resource" |
| 137 |
$privateKey = openssl_pkey_get_private( |
| 138 |
file_get_contents($privateKeyFile), |
| 139 |
$passphrase |
| 140 |
); |
| 141 |
|
| 142 |
$payload = [ |
| 143 |
'iss' => 'example.org', |
| 144 |
'aud' => 'example.com', |
| 145 |
'iat' => 1356999524, |
| 146 |
'nbf' => 1357000000 |
| 147 |
]; |
| 148 |
|
| 149 |
$jwt = JWT::encode($payload, $privateKey, 'RS256'); |
| 150 |
echo "Encode:\n" . print_r($jwt, true) . "\n"; |
| 151 |
|
| 152 |
// Get public key from the private key, or pull from from a file. |
| 153 |
$publicKey = openssl_pkey_get_details($privateKey)['key']; |
| 154 |
|
| 155 |
$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256')); |
| 156 |
echo "Decode:\n" . print_r((array) $decoded, true) . "\n"; |
| 157 |
``` |
| 158 |
|
| 159 |
Example with EdDSA (libsodium and Ed25519 signature) |
| 160 |
---------------------------- |
| 161 |
```php |
| 162 |
use Firebase\JWT\JWT; |
| 163 |
use Firebase\JWT\Key; |
| 164 |
|
| 165 |
// Public and private keys are expected to be Base64 encoded. The last |
| 166 |
// non-empty line is used so that keys can be generated with |
| 167 |
// sodium_crypto_sign_keypair(). The secret keys generated by other tools may |
| 168 |
// need to be adjusted to match the input expected by libsodium. |
| 169 |
|
| 170 |
$keyPair = sodium_crypto_sign_keypair(); |
| 171 |
|
| 172 |
$privateKey = base64_encode(sodium_crypto_sign_secretkey($keyPair)); |
| 173 |
|
| 174 |
$publicKey = base64_encode(sodium_crypto_sign_publickey($keyPair)); |
| 175 |
|
| 176 |
$payload = [ |
| 177 |
'iss' => 'example.org', |
| 178 |
'aud' => 'example.com', |
| 179 |
'iat' => 1356999524, |
| 180 |
'nbf' => 1357000000 |
| 181 |
]; |
| 182 |
|
| 183 |
$jwt = JWT::encode($payload, $privateKey, 'EdDSA'); |
| 184 |
echo "Encode:\n" . print_r($jwt, true) . "\n"; |
| 185 |
|
| 186 |
$decoded = JWT::decode($jwt, new Key($publicKey, 'EdDSA')); |
| 187 |
echo "Decode:\n" . print_r((array) $decoded, true) . "\n"; |
| 188 |
```` |
| 189 |
|
| 190 |
Using JWKs |
| 191 |
---------- |
| 192 |
|
| 193 |
```php |
| 194 |
use Firebase\JWT\JWK; |
| 195 |
use Firebase\JWT\JWT; |
| 196 |
|
| 197 |
// Set of keys. The "keys" key is required. For example, the JSON response to |
| 198 |
// this endpoint: https://www.gstatic.com/iap/verify/public_key-jwk |
| 199 |
$jwks = ['keys' => []]; |
| 200 |
|
| 201 |
// JWK::parseKeySet($jwks) returns an associative array of **kid** to Firebase\JWT\Key |
| 202 |
// objects. Pass this as the second parameter to JWT::decode. |
| 203 |
JWT::decode($payload, JWK::parseKeySet($jwks)); |
| 204 |
``` |
| 205 |
|
| 206 |
Using Cached Key Sets |
| 207 |
--------------------- |
| 208 |
|
| 209 |
The `CachedKeySet` class can be used to fetch and cache JWKS (JSON Web Key Sets) from a public URI. |
| 210 |
This has the following advantages: |
| 211 |
|
| 212 |
1. The results are cached for performance. |
| 213 |
2. If an unrecognized key is requested, the cache is refreshed, to accomodate for key rotation. |
| 214 |
3. If rate limiting is enabled, the JWKS URI will not make more than 10 requests a second. |
| 215 |
|
| 216 |
```php |
| 217 |
use Firebase\JWT\CachedKeySet; |
| 218 |
use Firebase\JWT\JWT; |
| 219 |
|
| 220 |
// The URI for the JWKS you wish to cache the results from |
| 221 |
$jwksUri = 'https://www.gstatic.com/iap/verify/public_key-jwk'; |
| 222 |
|
| 223 |
// Create an HTTP client (can be any PSR-7 compatible HTTP client) |
| 224 |
$httpClient = new GuzzleHttp\Client(); |
| 225 |
|
| 226 |
// Create an HTTP request factory (can be any PSR-17 compatible HTTP request factory) |
| 227 |
$httpFactory = new GuzzleHttp\Psr\HttpFactory(); |
| 228 |
|
| 229 |
// Create a cache item pool (can be any PSR-6 compatible cache item pool) |
| 230 |
$cacheItemPool = Phpfastcache\CacheManager::getInstance('files'); |
| 231 |
|
| 232 |
$keySet = new CachedKeySet( |
| 233 |
$jwksUri, |
| 234 |
$httpClient, |
| 235 |
$httpFactory, |
| 236 |
$cacheItemPool, |
| 237 |
null, // $expiresAfter int seconds to set the JWKS to expire |
| 238 |
true // $rateLimit true to enable rate limit of 10 RPS on lookup of invalid keys |
| 239 |
); |
| 240 |
|
| 241 |
$jwt = 'eyJhbGci...'; // Some JWT signed by a key from the $jwkUri above |
| 242 |
$decoded = JWT::decode($jwt, $keySet); |
| 243 |
``` |
| 244 |
|
| 245 |
Miscellaneous |
| 246 |
------------- |
| 247 |
|
| 248 |
#### Exception Handling |
| 249 |
|
| 250 |
When a call to `JWT::decode` is invalid, it will throw one of the following exceptions: |
| 251 |
|
| 252 |
```php |
| 253 |
use Firebase\JWT\JWT; |
| 254 |
use Firebase\JWT\SignatureInvalidException; |
| 255 |
use Firebase\JWT\BeforeValidException; |
| 256 |
use Firebase\JWT\ExpiredException; |
| 257 |
use DomainException; |
| 258 |
use InvalidArgumentException; |
| 259 |
use UnexpectedValueException; |
| 260 |
|
| 261 |
try { |
| 262 |
$decoded = JWT::decode($payload, $keys); |
| 263 |
} catch (InvalidArgumentException $e) { |
| 264 |
// provided key/key-array is empty or malformed. |
| 265 |
} catch (DomainException $e) { |
| 266 |
// provided algorithm is unsupported OR |
| 267 |
// provided key is invalid OR |
| 268 |
// unknown error thrown in openSSL or libsodium OR |
| 269 |
// libsodium is required but not available. |
| 270 |
} catch (SignatureInvalidException $e) { |
| 271 |
// provided JWT signature verification failed. |
| 272 |
} catch (BeforeValidException $e) { |
| 273 |
// provided JWT is trying to be used before "nbf" claim OR |
| 274 |
// provided JWT is trying to be used before "iat" claim. |
| 275 |
} catch (ExpiredException $e) { |
| 276 |
// provided JWT is trying to be used after "exp" claim. |
| 277 |
} catch (UnexpectedValueException $e) { |
| 278 |
// provided JWT is malformed OR |
| 279 |
// provided JWT is missing an algorithm / using an unsupported algorithm OR |
| 280 |
// provided JWT algorithm does not match provided key OR |
| 281 |
// provided key ID in key/key-array is empty or invalid. |
| 282 |
} |
| 283 |
``` |
| 284 |
|
| 285 |
All exceptions in the `Firebase\JWT` namespace extend `UnexpectedValueException`, and can be simplified |
| 286 |
like this: |
| 287 |
|
| 288 |
```php |
| 289 |
try { |
| 290 |
$decoded = JWT::decode($payload, $keys); |
| 291 |
} catch (LogicException $e) { |
| 292 |
// errors having to do with environmental setup or malformed JWT Keys |
| 293 |
} catch (UnexpectedValueException $e) { |
| 294 |
// errors having to do with JWT signature and claims |
| 295 |
} |
| 296 |
``` |
| 297 |
|
| 298 |
#### Casting to array |
| 299 |
|
| 300 |
The return value of `JWT::decode` is the generic PHP object `stdClass`. If you'd like to handle with arrays |
| 301 |
instead, you can do the following: |
| 302 |
|
| 303 |
```php |
| 304 |
// return type is stdClass |
| 305 |
$decoded = JWT::decode($payload, $keys); |
| 306 |
|
| 307 |
// cast to array |
| 308 |
$decoded = json_decode(json_encode($decoded), true); |
| 309 |
``` |
| 310 |
|
| 311 |
Tests |
| 312 |
----- |
| 313 |
Run the tests using phpunit: |
| 314 |
|
| 315 |
```bash |
| 316 |
$ pear install PHPUnit |
| 317 |
$ phpunit --configuration phpunit.xml.dist |
| 318 |
PHPUnit 3.7.10 by Sebastian Bergmann. |
| 319 |
..... |
| 320 |
Time: 0 seconds, Memory: 2.50Mb |
| 321 |
OK (5 tests, 5 assertions) |
| 322 |
``` |
| 323 |
|
| 324 |
New Lines in private keys |
| 325 |
----- |
| 326 |
|
| 327 |
If your private key contains `\n` characters, be sure to wrap it in double quotes `""` |
| 328 |
and not single quotes `''` in order to properly interpret the escaped characters. |
| 329 |
|
| 330 |
License |
| 331 |
------- |
| 332 |
[](http://opensource.org/licenses/BSD-3-Clause3-Clause BSD](http://opensource.org/licenses/BSD-3-Clause](http://opensource.org/licenses/BSD-3-Clause). |
| 333 |
|