-
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathJWT.php
More file actions
301 lines (254 loc) · 8.17 KB
/
JWT.php
File metadata and controls
301 lines (254 loc) · 8.17 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
<?php
declare(strict_types=1);
/*
* This file is part of the PHP-JWT package.
*
* (c) Jitendra Adhikari <jiten.adhikary@gmail.com>
* <https://github.com/adhocore>
*
* Licensed under MIT license.
*/
namespace Ahc\Jwt;
use function array_merge;
use function base64_decode;
use function base64_encode;
use function explode;
use function hash_equals;
use function hash_hmac;
use function is_array;
use function json_decode;
use function json_encode;
use function openssl_pkey_get_details;
use function openssl_sign;
use function openssl_verify;
use function reset;
use function rtrim;
use function strtr;
use function substr_count;
use function time;
use stdClass;
use const JSON_UNESCAPED_SLASHES;
use const OPENSSL_ALGO_SHA256;
use const OPENSSL_ALGO_SHA384;
use const OPENSSL_ALGO_SHA512;
/**
* JSON Web Token (JWT) implementation in PHP5.5+.
*
* @author Jitendra Adhikari <jiten.adhikary@gmail.com>
* @license MIT
*
* @link https://github.com/adhocore/jwt
*/
class JWT
{
use ValidatesJWT;
const ERROR_KEY_EMPTY = 10;
const ERROR_KEY_INVALID = 12;
const ERROR_ALGO_UNSUPPORTED = 20;
const ERROR_ALGO_MISSING = 22;
const ERROR_INVALID_MAXAGE = 30;
const ERROR_INVALID_LEEWAY = 32;
const ERROR_JSON_FAILED = 40;
const ERROR_TOKEN_INVALID = 50;
const ERROR_TOKEN_EXPIRED = 52;
const ERROR_TOKEN_NOT_NOW = 54;
const ERROR_SIGNATURE_FAILED = 60;
const ERROR_KID_UNKNOWN = 70;
/** @var array Supported Signing algorithms. */
protected $algos = [
'HS256' => 'sha256',
'HS384' => 'sha384',
'HS512' => 'sha512',
'RS256' => OPENSSL_ALGO_SHA256,
'RS384' => OPENSSL_ALGO_SHA384,
'RS512' => OPENSSL_ALGO_SHA512,
];
/** @var string|resource The signature key. */
protected $key;
/** @var array The list of supported keys with id. */
protected $keys = [];
/** @var int|null Use setTestTimestamp() to set custom value for time(). Useful for testability. */
protected $timestamp;
/** @var string The JWT signing algorithm. Defaults to HS256. */
protected $algo = 'HS256';
/** @var int The JWT TTL in seconds. Defaults to 1 hour. */
protected $maxAge = 3600;
/** @var int Grace period in seconds to allow for clock skew. Defaults to 0 seconds. */
protected $leeway = 0;
/** @var string|null The passphrase for RSA signing (optional). */
protected $passphrase;
/**
* Constructor.
*
* @param string|resource $key The signature key. For RS* it should be file path or resource of private key.
* @param string $algo The algorithm to sign/verify the token.
* @param int $maxAge The TTL of token to be used to determine expiry if `iat` claim is present.
* This is also used to provide default `exp` claim in case it is missing.
* @param int $leeway Leeway for clock skew. Shouldnot be more than 2 minutes (120s).
* @param string $pass The passphrase (only for RS* algos).
*/
public function __construct(
$key,
string $algo = 'HS256',
int $maxAge = 3600,
int $leeway = 0,
string $pass = null
) {
$this->validateConfig($key, $algo, $maxAge, $leeway);
if (is_array($key)) {
$this->registerKeys($key);
$key = reset($key); // use first one!
}
$this->key = $key;
$this->algo = $algo;
$this->maxAge = $maxAge;
$this->leeway = $leeway;
$this->passphrase = $pass;
}
/**
* Register keys for `kid` support.
*
* @param array $keys Use format: ['<kid>' => '<key data>', '<kid2>' => '<key data2>']
*
* @return self
*/
public function registerKeys(array $keys): self
{
$this->keys = array_merge($this->keys, $keys);
return $this;
}
/**
* Encode payload as JWT token.
*
* @param array $payload
* @param array $header Extra header (if any) to append.
*
* @return string URL safe JWT token.
*/
public function encode(array $payload, array $header = []): string
{
$header = ['typ' => 'JWT', 'alg' => $this->algo] + $header;
$this->validateKid($header);
if (!isset($payload['iat']) && !isset($payload['exp'])) {
$payload['exp'] = ($this->timestamp ?: time()) + $this->maxAge;
}
$header = $this->urlSafeEncode($header);
$payload = $this->urlSafeEncode($payload);
$signature = $this->urlSafeEncode($this->sign($header . '.' . $payload));
return $header . '.' . $payload . '.' . $signature;
}
/**
* Decode JWT token and return original payload.
*
* @param string $token
* @param bool $verify
*
* @throws JWTException
*
* @return array
*/
public function decode(string $token, bool $verify = true): array
{
if (substr_count($token, '.') < 2) {
throw new JWTException('Invalid token: Incomplete segments', static::ERROR_TOKEN_INVALID);
}
$token = explode('.', $token, 3);
if (!$verify) {
return (array) $this->urlSafeDecode($token[1]);
}
$this->validateHeader((array) $this->urlSafeDecode($token[0]));
// Validate signature.
if (!$this->verify($token[0] . '.' . $token[1], $token[2])) {
throw new JWTException('Invalid token: Signature failed', static::ERROR_SIGNATURE_FAILED);
}
$payload = (array) $this->urlSafeDecode($token[1]);
$this->validateTimestamps($payload);
return $payload;
}
/**
* Spoof current timestamp for testing.
*
* @param int|null $timestamp
*/
public function setTestTimestamp(int $timestamp = null): self
{
$this->timestamp = $timestamp;
return $this;
}
/**
* Sign the input with configured key and return the signature.
*
* @param string $input
*
* @return string
*/
protected function sign(string $input): string
{
// HMAC SHA.
if (strpos($this->algo, 'HS') === 0) {
return hash_hmac($this->algos[$this->algo], $input, $this->key, true);
}
$this->validateKey();
openssl_sign($input, $signature, $this->key, $this->algos[$this->algo]);
return $signature;
}
/**
* Verify the signature of given input.
*
* @param string $input
* @param string $signature
*
* @throws JWTException When key is invalid.
*
* @return bool
*/
protected function verify(string $input, string $signature): bool
{
$algo = $this->algos[$this->algo];
// HMAC SHA.
if (strpos($this->algo, 'HS') === 0) {
return hash_equals($this->urlSafeEncode(hash_hmac($algo, $input, $this->key, true)), $signature);
}
$this->validateKey();
$pubKey = openssl_pkey_get_details($this->key)['key'];
return openssl_verify($input, $this->urlSafeDecode($signature, false), $pubKey, $algo) === 1;
}
/**
* URL safe base64 encode.
*
* First serialized the payload as json if it is an array.
*
* @param array|string $data
*
* @throws JWTException When JSON encode fails.
*
* @return string
*/
protected function urlSafeEncode($data): string
{
if (is_array($data)) {
$data = json_encode($data, JSON_UNESCAPED_SLASHES);
$this->validateLastJson();
}
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
/**
* URL safe base64 decode.
*
* @param array|string $data
* @param bool $asJson Whether to parse as JSON (defaults to true).
*
* @return array|stdClass|string
*@throws JWTException When JSON encode fails.
*
*/
protected function urlSafeDecode($data, bool $asJson = true)
{
if (!$asJson) {
return base64_decode(strtr($data, '-_', '+/'));
}
$data = json_decode(base64_decode(strtr($data, '-_', '+/')), false);
$this->validateLastJson();
return $data;
}
}