@@ -18,49 +18,70 @@ composer require adhocore/jwt
1818```
1919
2020## Usage
21+
2122``` php
2223use Ahc\Jwt\JWT;
2324
2425// Instantiate with key, algo, maxAge and leeway.
2526$jwt = new JWT('secret', 'HS256', 3600, 10);
27+ ```
2628
27- // Only the key is required. Defaults will be used for the rest:
28- // algo = HS256, maxAge = 3600, leeway = 0
29+ Only the key is required. Defaults will be used for the rest:
30+ ``` php
2931$jwt = new JWT('secret');
32+ // algo = HS256, maxAge = 3600, leeway = 0
33+ ```
3034
31- // For RS* algo, the key should be either a resource like below:
35+ For ` RS* ` algo, the key should be either a resource like below:
36+ ``` php
3237$key = openssl_pkey_new(['digest_alg' => 'sha256', 'private_key_bits' => 1024, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
38+
3339// OR, a string with full path to the RSA private key like below:
3440$key = '/path/to/rsa.key';
41+
3542// Then, instantiate JWT with this key and RS* as algo:
3643$jwt = new JWT($key, 'RS384');
44+ ```
3745
38- // Generate JWT token from payload array.
46+ Generate JWT token from payload array:
47+ ``` php
3948$token = $jwt->encode([
4049 'uid' => 1,
4150 'aud' => 'http://site.com',
4251 'scopes' => ['user'],
4352 'iss' => 'http://api.mysite.com',
4453]);
54+ ```
4555
46- // Retrieve the payload array.
56+ Retrieve the payload array:
57+ ``` php
4758$payload = $jwt->decode($token);
59+ ```
4860
49- // Oneliner.
61+ Oneliner:
62+ ```
5063$token = (new JWT('topSecret', 'HS512', 1800))->encode(['uid' => 1, 'scopes' => ['user']]));
5164$payload = (new JWT('topSecret', 'HS512', 1800))->decode($token);
65+ ```
66+
67+ *** Pro***
5268
53- // Can pass extra headers into encode() with second parameter.
69+ Can pass extra headers into encode() with second parameter:
70+ ``` php
5471$token = $jwt->encode($payload, ['hdr' => 'hdr_value']);
72+ ```
5573
56- // Spoof time() for testing token expiry.
74+ Spoof time() for testing token expiry:
75+ ``` php
5776$jwt->setTestTimestamp(time() + 10000);
77+
5878// Throws Exception.
5979$jwt->parse($token);
80+ ```
6081
61- // Call again without parameter to stop spoofing time().
82+ Call again without parameter to stop spoofing time():
83+ ``` php
6284$jwt->setTestTimestamp();
63-
6485```
6586
6687## Features
0 commit comments