PluginProbe
Gmail SMTP / trunk
Gmail SMTP vtrunk
1.2.3.21 1.2.3.20 trunk 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 1.1.9 1.2.0 1.2.3.14 1.2.3.15 1.2.3.16 1.2.3.18 1.2.3.5
gmail-smtp / google-api-php-client / vendor / firebase / php-jwt / README.md

README.md in Gmail SMTP trunk, at google-api-php-client/vendor/firebase/php-jwt/README.md

458 lines 14.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 ![Build Status](https://github.com/firebase/php-jwt/actions/workflows/tests.yml/badge.svg)
2 [](https://packagist.org/packages/firebase/php-jwt![Latest Stable Version](https://poser.pugx.org/firebase/php-jwt/v/stable)](https://packagist.org/packages/firebase/php-jwt](https://packagist.org/packages/firebase/php-jwt)
3 [](https://packagist.org/packages/firebase/php-jwt![Total Downloads](https://poser.pugx.org/firebase/php-jwt/downloads)](https://packagist.org/packages/firebase/php-jwt](https://packagist.org/packages/firebase/php-jwt)
4 [](https://packagist.org/packages/firebase/php-jwt![License](https://poser.pugx.org/firebase/php-jwt/license)](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 env 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_of_sufficient_length';
33 $payload = [
34 'iss' => 'example.org',
35 'aud' => '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 print_r($decoded);
49
50 // Pass a stdClass in as the third parameter to get the decoded header values
51 $headers = new stdClass();
52 $decoded = JWT::decode($jwt, new Key($key, 'HS256'), $headers);
53 print_r($headers);
54
55 /*
56 NOTE: This will now be an object instead of an associative array. To get
57 an associative array, you will need to cast it as such:
58 */
59
60 $decoded_array = (array) $decoded;
61
62 /**
63 * You can add a leeway to account for when there is a clock skew times between
64 * the signing and verifying servers. It is recommended that this leeway should
65 * not be bigger than a few minutes.
66 *
67 * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
68 */
69 JWT::$leeway = 60; // $leeway in seconds
70 $decoded = JWT::decode($jwt, new Key($key, 'HS256'));
71 ```
72
73 ## Example encode/decode headers
74
75 Decoding the JWT headers without verifying the JWT first is NOT recommended, and is not supported by
76 this library. This is because without verifying the JWT, the header values could have been tampered with.
77 Any value pulled from an unverified header should be treated as if it could be any string sent in from an
78 attacker. If this is something you still want to do in your application for whatever reason, it's possible to
79 decode the header values manually simply by calling `json_decode` and `base64_decode` on the JWT
80 header part:
81 ```php
82 use Firebase\JWT\JWT;
83
84 $key = 'example_key_of_sufficient_length';
85 $payload = [
86 'iss' => 'example.org',
87 'aud' => 'example.com',
88 'iat' => 1356999524,
89 'nbf' => 1357000000
90 ];
91
92 $headers = [
93 'x-forwarded-for' => 'www.google.com'
94 ];
95
96 // Encode headers in the JWT string
97 $jwt = JWT::encode($payload, $key, 'HS256', null, $headers);
98
99 // Decode headers from the JWT string WITHOUT validation
100 // **IMPORTANT**: This operation is vulnerable to attacks, as the JWT has not yet been verified.
101 // These headers could be any value sent by an attacker.
102 list($headersB64, $payloadB64, $sig) = explode('.', $jwt);
103 $decoded = json_decode(base64_decode($headersB64), true);
104
105 print_r($decoded);
106 ```
107
108 ## Example with RS256 (openssl)
109
110 ```php
111 use Firebase\JWT\JWT;
112 use Firebase\JWT\Key;
113
114 $privateKey = <<<EOD
115 -----BEGIN RSA PRIVATE KEY-----
116 MIIEowIBAAKCAQEAuzWHNM5f+amCjQztc5QTfJfzCC5J4nuW+L/aOxZ4f8J3Frew
117 M2c/dufrnmedsApb0By7WhaHlcqCh/ScAPyJhzkPYLae7bTVro3hok0zDITR8F6S
118 JGL42JAEUk+ILkPI+DONM0+3vzk6Kvfe548tu4czCuqU8BGVOlnp6IqBHhAswNMM
119 78pos/2z0CjPM4tbeXqSTTbNkXRboxjU29vSopcT51koWOgiTf3C7nJUoMWZHZI5
120 HqnIhPAG9yv8HAgNk6CMk2CadVHDo4IxjxTzTTqo1SCSH2pooJl9O8at6kkRYsrZ
121 WwsKlOFE2LUce7ObnXsYihStBUDoeBQlGG/BwQIDAQABAoIBAFtGaOqNKGwggn9k
122 6yzr6GhZ6Wt2rh1Xpq8XUz514UBhPxD7dFRLpbzCrLVpzY80LbmVGJ9+1pJozyWc
123 VKeCeUdNwbqkr240Oe7GTFmGjDoxU+5/HX/SJYPpC8JZ9oqgEA87iz+WQX9hVoP2
124 oF6EB4ckDvXmk8FMwVZW2l2/kd5mrEVbDaXKxhvUDf52iVD+sGIlTif7mBgR99/b
125 c3qiCnxCMmfYUnT2eh7Vv2LhCR/G9S6C3R4lA71rEyiU3KgsGfg0d82/XWXbegJW
126 h3QbWNtQLxTuIvLq5aAryV3PfaHlPgdgK0ft6ocU2de2FagFka3nfVEyC7IUsNTK
127 bq6nhAECgYEA7d/0DPOIaItl/8BWKyCuAHMss47j0wlGbBSHdJIiS55akMvnAG0M
128 39y22Qqfzh1at9kBFeYeFIIU82ZLF3xOcE3z6pJZ4Dyvx4BYdXH77odo9uVK9s1l
129 3T3BlMcqd1hvZLMS7dviyH79jZo4CXSHiKzc7pQ2YfK5eKxKqONeXuECgYEAyXlG
130 vonaus/YTb1IBei9HwaccnQ/1HRn6MvfDjb7JJDIBhNClGPt6xRlzBbSZ73c2QEC
131 6Fu9h36K/HZ2qcLd2bXiNyhIV7b6tVKk+0Psoj0dL9EbhsD1OsmE1nTPyAc9XZbb
132 OPYxy+dpBCUA8/1U9+uiFoCa7mIbWcSQ+39gHuECgYAz82pQfct30aH4JiBrkNqP
133 nJfRq05UY70uk5k1u0ikLTRoVS/hJu/d4E1Kv4hBMqYCavFSwAwnvHUo51lVCr/y
134 xQOVYlsgnwBg2MX4+GjmIkqpSVCC8D7j/73MaWb746OIYZervQ8dbKahi2HbpsiG
135 8AHcVSA/agxZr38qvWV54QKBgCD5TlDE8x18AuTGQ9FjxAAd7uD0kbXNz2vUYg9L
136 hFL5tyL3aAAtUrUUw4xhd9IuysRhW/53dU+FsG2dXdJu6CxHjlyEpUJl2iZu/j15
137 YnMzGWHIEX8+eWRDsw/+Ujtko/B7TinGcWPz3cYl4EAOiCeDUyXnqnO1btCEUU44
138 DJ1BAoGBAJuPD27ErTSVtId90+M4zFPNibFP50KprVdc8CR37BE7r8vuGgNYXmnI
139 RLnGP9p3pVgFCktORuYS2J/6t84I3+A17nEoB4xvhTLeAinAW/uTQOUmNicOP4Ek
140 2MsLL2kHgL8bLTmvXV4FX+PXphrDKg1XxzOYn0otuoqdAQrkK4og
141 -----END RSA PRIVATE KEY-----
142 EOD;
143
144 $publicKey = <<<EOD
145 -----BEGIN PUBLIC KEY-----
146 MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzWHNM5f+amCjQztc5QT
147 fJfzCC5J4nuW+L/aOxZ4f8J3FrewM2c/dufrnmedsApb0By7WhaHlcqCh/ScAPyJ
148 hzkPYLae7bTVro3hok0zDITR8F6SJGL42JAEUk+ILkPI+DONM0+3vzk6Kvfe548t
149 u4czCuqU8BGVOlnp6IqBHhAswNMM78pos/2z0CjPM4tbeXqSTTbNkXRboxjU29vS
150 opcT51koWOgiTf3C7nJUoMWZHZI5HqnIhPAG9yv8HAgNk6CMk2CadVHDo4IxjxTz
151 TTqo1SCSH2pooJl9O8at6kkRYsrZWwsKlOFE2LUce7ObnXsYihStBUDoeBQlGG/B
152 wQIDAQAB
153 -----END PUBLIC KEY-----
154 EOD;
155
156 $payload = [
157 'iss' => 'example.org',
158 'aud' => 'example.com',
159 'iat' => 1356999524,
160 'nbf' => 1357000000
161 ];
162
163 $jwt = JWT::encode($payload, $privateKey, 'RS256');
164 echo "Encode:\n" . print_r($jwt, true) . "\n";
165
166 $decoded = JWT::decode($jwt, new Key($publicKey, 'RS256'));
167
168 /*
169 NOTE: This will now be an object instead of an associative array. To get
170 an associative array, you will need to cast it as such:
171 */
172
173 $decoded_array = (array) $decoded;
174 echo "Decode:\n" . print_r($decoded_array, true) . "\n";
175 ```
176
177 ## Example with a passphrase
178
179 ```php
180 use Firebase\JWT\JWT;
181 use Firebase\JWT\Key;
182
183 // Your passphrase
184 $passphrase = '[YOUR_PASSPHRASE]';
185
186 // Your private key file with passphrase
187 // Can be generated with "ssh-keygen -t rsa -m pem"
188 $privateKeyFile = '/path/to/key-with-passphrase.pem';
189
190 /** @var OpenSSLAsymmetricKey $privateKey */
191 $privateKey = openssl_pkey_get_private(
192 file_get_contents($privateKeyFile),
193 $passphrase
194 );
195
196 $payload = [
197 'iss' => 'example.org',
198 'aud' => 'example.com',
199 'iat' => 1356999524,
200 'nbf' => 1357000000
201 ];
202
203 $jwt = JWT::encode($payload, $privateKey, 'RS256');
204 echo "Encode:\n" . print_r($jwt, true) . "\n";
205
206 // Get public key from the private key, or pull from from a file.
207 $publicKey = openssl_pkey_get_details($privateKey)['key'];
208
209 $decoded = JWT::decode($jwt, new Key($publicKey, 'RS256'));
210 echo "Decode:\n" . print_r((array) $decoded, true) . "\n";
211 ```
212
213 ## Example with EdDSA (libsodium and Ed25519 signature)
214
215 ```php
216 use Firebase\JWT\JWT;
217 use Firebase\JWT\Key;
218
219 // Public and private keys are expected to be Base64 encoded. The last
220 // non-empty line is used so that keys can be generated with
221 // sodium_crypto_sign_keypair(). The secret keys generated by other tools may
222 // need to be adjusted to match the input expected by libsodium.
223
224 $keyPair = sodium_crypto_sign_keypair();
225
226 $privateKey = base64_encode(sodium_crypto_sign_secretkey($keyPair));
227
228 $publicKey = base64_encode(sodium_crypto_sign_publickey($keyPair));
229
230 $payload = [
231 'iss' => 'example.org',
232 'aud' => 'example.com',
233 'iat' => 1356999524,
234 'nbf' => 1357000000
235 ];
236
237 $jwt = JWT::encode($payload, $privateKey, 'EdDSA');
238 echo "Encode:\n" . print_r($jwt, true) . "\n";
239
240 $decoded = JWT::decode($jwt, new Key($publicKey, 'EdDSA'));
241 echo "Decode:\n" . print_r((array) $decoded, true) . "\n";
242 ```
243
244 ## Example with multiple keys
245
246 ```php
247 use Firebase\JWT\JWT;
248 use Firebase\JWT\Key;
249
250 // Example RSA keys from previous example
251 // $privateRsKey = '...';
252 // $publicRsKey = '...';
253
254 // Example EdDSA keys from previous example
255 // $privateEcKey = '...';
256 // $publicEcKey = '...';
257
258 $payload = [
259 'iss' => 'example.org',
260 'aud' => 'example.com',
261 'iat' => 1356999524,
262 'nbf' => 1357000000
263 ];
264
265 $jwt1 = JWT::encode($payload, $privateRsKey, 'RS256', 'kid1');
266 $jwt2 = JWT::encode($payload, $privateEcKey, 'EdDSA', 'kid2');
267 echo "Encode 1:\n" . print_r($jwt1, true) . "\n";
268 echo "Encode 2:\n" . print_r($jwt2, true) . "\n";
269
270 $keys = [
271 'kid1' => new Key($publicRsKey, 'RS256'),
272 'kid2' => new Key($publicEcKey, 'EdDSA'),
273 ];
274
275 $decoded1 = JWT::decode($jwt1, $keys);
276 $decoded2 = JWT::decode($jwt2, $keys);
277
278 echo "Decode 1:\n" . print_r((array) $decoded1, true) . "\n";
279 echo "Decode 2:\n" . print_r((array) $decoded2, true) . "\n";
280 ```
281
282 ## Example with PS256
283
284 ### Note
285 PHP's OpenSSL extension does not support RSASSA-PSS signatures (PS256) by default, so we provide support via a soft dependency on the [](https://github.com/phpseclib/phpseclibphpseclib/phpseclib](https://github.com/phpseclib/phpseclib](https://github.com/phpseclib/phpseclib) library. It is necessary to install this library in your project if you plan to use PS256.
286 ```bash
287 composer install phpseclib/phpseclib:^3.0
288 ```
289
290 ```php
291 use Firebase\JWT\JWT;
292 use Firebase\JWT\Key;
293
294 $privateRsKey = '-----BEGIN RSA PRIVATE KEY----- ...';
295 $publicKey = '-----BEGIN PUBLIC KEY----- ...';
296
297 $payload = [
298 'iss' => 'example.org',
299 'aud' => 'example.com',
300 'iat' => 1356999524,
301 'nbf' => 1357000000
302 ];
303
304 /**
305 * PS256 support requires phpseclib/phpseclib
306 */
307 $jwt = JWT::encode($payload, $privateRsKey, 'PS256', 'keyid');
308 echo "Encode:\n" . print_r($jwt, true) . "\n";
309
310 $decoded = JWT::decode($jwt, new Key($publicKey, 'PS256'));
311 echo "Decode:\n" . print_r((array) $decoded, true) . "\n";
312 ```
313
314 ## Using JWKs
315
316 ```php
317 use Firebase\JWT\JWK;
318 use Firebase\JWT\JWT;
319
320 // Set of keys. The "keys" key is required. For example, the JSON response to
321 // this endpoint: https://www.gstatic.com/iap/verify/public_key-jwk
322 $jwks = ['keys' => []];
323
324 // JWK::parseKeySet($jwks) returns an associative array of **kid** to Firebase\JWT\Key
325 // objects. Pass this as the second parameter to JWT::decode.
326 $decoded = JWT::decode($jwt, JWK::parseKeySet($jwks));
327 print_r($decoded);
328 ```
329
330 ## Using Cached Key Sets
331
332 The `CachedKeySet` class can be used to fetch and cache JWKS (JSON Web Key Sets) from a public URI.
333 This has the following advantages:
334
335 1. The results are cached for performance.
336 2. If an unrecognized key is requested, the cache is refreshed, to accomodate for key rotation.
337 3. If rate limiting is enabled, the JWKS URI will not make more than 10 requests a second.
338
339 ```php
340 use Firebase\JWT\CachedKeySet;
341 use Firebase\JWT\JWT;
342
343 // The URI for the JWKS you wish to cache the results from
344 $jwksUri = 'https://www.gstatic.com/iap/verify/public_key-jwk';
345
346 // Create an HTTP client (can be any PSR-7 compatible HTTP client)
347 $httpClient = new GuzzleHttp\Client();
348
349 // Create an HTTP request factory (can be any PSR-17 compatible HTTP request factory)
350 $httpFactory = new GuzzleHttp\Psr7\HttpFactory();
351
352 // Create a cache item pool (can be any PSR-6 compatible cache item pool)
353 $cacheItemPool = Phpfastcache\CacheManager::getInstance('files');
354
355 $keySet = new CachedKeySet(
356 $jwksUri,
357 $httpClient,
358 $httpFactory,
359 $cacheItemPool,
360 null, // $expiresAfter int seconds to set the JWKS to expire
361 true // $rateLimit true to enable rate limit of 10 RPS on lookup of invalid keys
362 );
363
364 $jwt = 'eyJhbGci...'; // Some JWT signed by a key from the $jwkUri above
365 $decoded = JWT::decode($jwt, $keySet);
366 ```
367
368 Miscellaneous
369 -------------
370
371 #### Exception Handling
372
373 When a call to `JWT::decode` is invalid, it will throw one of the following exceptions:
374
375 ```php
376 use Firebase\JWT\JWT;
377 use Firebase\JWT\SignatureInvalidException;
378 use Firebase\JWT\BeforeValidException;
379 use Firebase\JWT\ExpiredException;
380 use DomainException;
381 use InvalidArgumentException;
382 use UnexpectedValueException;
383
384 try {
385 $decoded = JWT::decode($jwt, $keys);
386 } catch (InvalidArgumentException $e) {
387 // provided key/key-array is empty or malformed.
388 } catch (DomainException $e) {
389 // provided algorithm is unsupported OR
390 // provided key is invalid OR
391 // unknown error thrown in openSSL or libsodium OR
392 // libsodium is required but not available.
393 } catch (SignatureInvalidException $e) {
394 // provided JWT signature verification failed.
395 } catch (BeforeValidException $e) {
396 // provided JWT is trying to be used before "nbf" claim OR
397 // provided JWT is trying to be used before "iat" claim.
398 } catch (ExpiredException $e) {
399 // provided JWT is trying to be used after "exp" claim.
400 } catch (UnexpectedValueException $e) {
401 // provided JWT is malformed OR
402 // provided JWT is missing an algorithm / using an unsupported algorithm OR
403 // provided JWT algorithm does not match provided key OR
404 // provided key ID in key/key-array is empty or invalid.
405 }
406 ```
407
408 All exceptions in the `Firebase\JWT` namespace extend `UnexpectedValueException`, and can be simplified
409 like this:
410
411 ```php
412 use Firebase\JWT\JWT;
413 use UnexpectedValueException;
414 try {
415 $decoded = JWT::decode($jwt, $keys);
416 } catch (LogicException $e) {
417 // errors having to do with environmental setup or malformed JWT Keys
418 } catch (UnexpectedValueException $e) {
419 // errors having to do with JWT signature and claims
420 }
421 ```
422
423 #### Casting to array
424
425 The return value of `JWT::decode` is the generic PHP object `stdClass`. If you'd like to handle with arrays
426 instead, you can do the following:
427
428 ```php
429 // return type is stdClass
430 $decoded = JWT::decode($jwt, $keys);
431
432 // cast to array
433 $decoded = json_decode(json_encode($decoded), true);
434 ```
435
436 Tests
437 -----
438 Run the tests using phpunit:
439
440 ```bash
441 $ composer update
442 $ vendor/bin/phpunit -c phpunit.xml.dist
443 PHPUnit 3.7.10 by Sebastian Bergmann.
444 .....
445 Time: 0 seconds, Memory: 2.50Mb
446 OK (5 tests, 5 assertions)
447 ```
448
449 New Lines in private keys
450 -----
451
452 If your private key contains `\n` characters, be sure to wrap it in double quotes `""`
453 and not single quotes `''` in order to properly interpret the escaped characters.
454
455 License
456 -------
457 [](http://opensource.org/licenses/BSD-3-Clause3-Clause BSD](http://opensource.org/licenses/BSD-3-Clause](http://opensource.org/licenses/BSD-3-Clause).
458