-
Notifications
You must be signed in to change notification settings - Fork 28
/
functions.jsconnect.php
1291 lines (1274 loc) · 44.2 KB
/
functions.jsconnect.php
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Vanilla\JsConnect {
/**
* This class contains backwards compatible methods for the v2.x jsConnect protocol.
*/
final class JsConnectJSONP
{
const VERSION = "2";
const TIMEOUT = 24 * 60;
const FIELD_MAP = ["uniqueid" => JsConnect::FIELD_UNIQUE_ID, "photourl" => JsConnect::FIELD_PHOTO];
/**
* Write the jsConnect string for single sign on.
*
* @param array $user An array containing information about the currently signed on user. If no user is signed in, this should be empty.
* @param array $request An array of the $_GET request.
* @param string $clientID The string client ID that you set up in the jsConnect settings page.
* @param string $secret The string secret that you set up in the jsConnect settings page.
* @param string|bool $secure Whether or not to check for security. This is one of these values.
* - true: Check for security and sign the response with an md5 hash.
* - false: Don't check for security, but sign the response with an md5 hash.
* - string: Check for security and sign the response with the given hash algorithm. See hash_algos() for what your server can support.
* - null: Don't check for security and don't sign the response.
* @since 1.1b Added the ability to provide a hash algorithm to $secure.
*/
public static function writeJsConnect($user, $request, $clientID, $secret, $secure = true) : void
{
if (isset($request["jwt"])) {
self::writeJWT($user, $request, $clientID, $secret);
} else {
self::writeJSONP($user, $request, $clientID, $secret, $secure);
}
}
/**
* This is a backwards compatible method to help migrate jsConnect to the KWT protocol.
*
* @param array $user
* @param array $query
* @param string $clientID
* @param string $secret
*/
protected static function writeJWT(array $user, array $query, string $clientID, string $secret) : void
{
$jsc = new JsConnect();
$jsc->setSigningCredentials($clientID, $secret);
foreach ($user as $key => $value) {
$lkey = strtolower($key);
if (isset(self::FIELD_MAP[$lkey])) {
$key = self::FIELD_MAP[$lkey];
}
$jsc->setUserField($key, $value);
}
$jsc->handleRequest($query);
}
/**
* Write the JSONP (v2) protocol response.
*
* @param array $user
* @param array $request
* @param string $clientID
* @param string $secret
* @param bool|string|null $secure
*/
protected static function writeJSONP(array $user, array $request, string $clientID, string $secret, $secure) : void
{
$user = array_change_key_case($user);
// Error checking.
if ($secure) {
// Check the client.
if (!isset($request["v"])) {
$error = ["error" => "invalid_request", "message" => "Missing the v parameter."];
} elseif ($request["v"] !== self::VERSION) {
$error = ["error" => "invalid_request", "message" => "Unsupported version {$request["v"]}."];
} elseif (!isset($request["client_id"])) {
$error = ["error" => "invalid_request", "message" => "Missing the client_id parameter."];
} elseif ($request["client_id"] != $clientID) {
$error = ["error" => "invalid_client", "message" => "Unknown client {$request["client_id"]}."];
} elseif (!isset($request["timestamp"]) && !isset($request["sig"])) {
if (count($user) > 0) {
// This isn't really an error, but we are just going to return public information when no signature is sent.
$error = ["name" => (string) @$user["name"], "photourl" => @$user["photourl"], "signedin" => true];
} else {
$error = ["name" => "", "photourl" => ""];
}
} elseif (!isset($request["timestamp"]) || !ctype_digit($request["timestamp"])) {
$error = ["error" => "invalid_request", "message" => "The timestamp parameter is missing or invalid."];
} elseif (!isset($request["sig"])) {
$error = ["error" => "invalid_request", "message" => "Missing the sig parameter."];
} elseif (abs($request["timestamp"] - self::timestamp()) > self::TIMEOUT) {
// Make sure the timestamp hasn't timeout
$error = ["error" => "invalid_request", "message" => "The timestamp is invalid."];
} elseif (!isset($request["nonce"])) {
$error = ["error" => "invalid_request", "message" => "Missing the nonce parameter."];
} elseif (!isset($request["ip"])) {
$error = ["error" => "invalid_request", "message" => "Missing the ip parameter."];
} else {
$signature = self::hash($request["ip"] . $request["nonce"] . $request["timestamp"] . $secret, $secure);
if ($signature != $request["sig"]) {
$error = ["error" => "access_denied", "message" => "Signature invalid."];
}
}
}
if (isset($error)) {
$result = $error;
} elseif (count($user) > 0) {
if ($secure === null) {
$result = $user;
} else {
$user["ip"] = $request["ip"];
$user["nonce"] = $request["nonce"];
$result = self::signJsConnect($user, $clientID, $secret, $secure, true);
/**
* @psalm-suppress PossiblyInvalidArrayOffset
*/
$result["v"] = self::VERSION;
}
} else {
$result = ["name" => "", "photourl" => ""];
}
$content = json_encode($result);
if (isset($request["callback"])) {
$content = "{$request["callback"]}({$content})";
}
if (!headers_sent()) {
$contentType = self::contentType($request);
header($contentType, true);
}
echo $content;
}
/**
* Get the current timestamp.
*
* @return int
*/
public static function timestamp()
{
return time();
}
/**
* Return the hash of a string.
*
* @param string $string The string to hash.
* @param string|bool $secure The hash algorithm to use. true means md5.
* @return string
*/
public static function hash($string, $secure = true)
{
if ($secure === true) {
$secure = "md5";
}
switch ($secure) {
case "sha1":
return sha1($string);
break;
case "md5":
case false:
return md5($string);
default:
return hash($secure, $string);
}
}
/**
* Sign a jsConnect array.
*
* @param array $data
* @param string $clientID
* @param string $secret
* @param string|bool $hashType
* @param bool $returnData
*
* @return array|string
*/
public static function signJsConnect(array $data, string $clientID, string $secret, $hashType, bool $returnData = false)
{
$normalizedData = array_change_key_case($data);
ksort($normalizedData);
foreach ($normalizedData as $key => $value) {
if ($value === null) {
$normalizedData[$key] = "";
}
}
// RFC1738 state that spaces are encoded as '+'.
$stringifiedData = http_build_query($normalizedData, "", "&", PHP_QUERY_RFC1738);
$signature = self::hash($stringifiedData . $secret, $hashType);
if ($returnData) {
$normalizedData["client_id"] = $clientID;
$normalizedData["sig"] = $signature;
return $normalizedData;
} else {
return $signature;
}
}
/**
* Based on a jsConnect request, determine the proper response content type.
*
* @param array $request
* @return string
*/
public static function contentType(array $request) : string
{
$isJsonp = isset($request["callback"]);
$contentType = $isJsonp ? "Content-Type: application/javascript; charset=utf-8" : "Content-Type: application/json; charset=utf-8";
return $contentType;
}
/**
* Generate an SSO string suitable for passing in the url for embedded SSO.
*
* @param array $user The user to sso.
* @param string $clientID Your client ID.
* @param string $secret Your secret.
* @return string
*/
public static function ssoString($user, $clientID, $secret)
{
if (!isset($user["client_id"])) {
$user["client_id"] = $clientID;
}
$string = base64_encode(json_encode($user));
$timestamp = time();
$hash = hash_hmac("sha1", "{$string} {$timestamp}", $secret);
$result = "{$string} {$hash} {$timestamp} hmacsha1";
return $result;
}
}
}
namespace Vanilla\JsConnect {
use Exception;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use UnexpectedValueException;
use Vanilla\JsConnect\Exceptions\FieldNotFoundException;
use Vanilla\JsConnect\Exceptions\InvalidValueException;
/**
* Handles the jsConnect protocol v3.x.
*/
class JsConnect
{
const VERSION = "php:3";
const FIELD_UNIQUE_ID = "id";
const FIELD_PHOTO = "photo";
const FIELD_NAME = "name";
const FIELD_EMAIL = "email";
const FIELD_ROLES = "roles";
const FIELD_JWT = "jwt";
const TIMEOUT = 10 * 60;
const ALLOWED_ALGORITHMS = ["ES256", "HS256", "HS384", "HS512", "RS256", "RS384", "RS512"];
const FIELD_STATE = "st";
const FIELD_USER = "u";
const FIELD_REDIRECT_URL = "rurl";
const FIELD_CLIENT_ID = "kid";
const FIELD_TARGET = "t";
/**
* @var \ArrayAccess
*/
protected $keys;
/**
* @var string string
*/
protected $signingClientID = "";
/**
* @var array
*/
protected $user = [];
/**
* @var bool
*/
protected $guest = false;
/**
* @var string
*/
protected $signingAlgorithm;
/**
* @var int
*/
protected $timeout = self::TIMEOUT;
/**
* JsConnect constructor.
*/
public function __construct()
{
$this->keys = new \ArrayObject();
$this->setSigningAlgorithm("HS256");
}
/**
* Validate a value that cannot be empty.
*
* @param mixed $value The value to test.
* @param string $valueName The name of the value for the exception message.
* @throws InvalidValueException Throws an exception when the value is empty.
*/
protected static function validateNotEmpty($value, string $valueName) : void
{
if ($value === null) {
throw new InvalidValueException("{$valueName} is required.");
}
if (empty($value)) {
throw new InvalidValueException("{$valueName} cannot be empty.");
}
}
/**
* Set the current user's email address.
*
* @param string $email
* @return $this
*/
public function setEmail(string $email)
{
return $this->setUserField(self::FIELD_EMAIL, $email);
}
/**
* Set a field on the current user.
*
* @param string $key The key on the user.
* @param string|int|bool|array|null $value The value to set. This must be a basic type that can be JSON encoded.
* @return $this
*/
public function setUserField(string $key, $value)
{
$this->user[$key] = $value;
return $this;
}
/**
* Set the current user's username.
*
* @param string $name
* @return $this
*/
public function setName(string $name)
{
return $this->setUserField(self::FIELD_NAME, $name);
}
/**
* Set the current user's avatar.
*
* @param string $photo
* @return $this
*/
public function setPhotoURL(string $photo)
{
return $this->setUserField(self::FIELD_PHOTO, $photo);
}
/**
* Set the current user's unique ID.
*
* @param string $id
* @return $this
*/
public function setUniqueID(string $id)
{
return $this->setUserField(self::FIELD_UNIQUE_ID, $id);
}
/**
* Handle the authentication request and redirect back to Vanilla.
*
* @param array $query
*/
public function handleRequest(array $query) : void
{
try {
$jwt = static::validateFieldExists(self::FIELD_JWT, $query, "querystring");
$location = $this->generateResponseLocation($jwt);
$this->redirect($location);
} catch (Exception $ex) {
echo htmlspecialchars($ex->getMessage());
}
}
/**
* Validate that a field exists in a collection.
*
* @param string $field The name of the field to validate.
* @param mixed $collection The collection to look at.
* @param string $collectionName The name of the collection.
* @param bool $validateEmpty If true, make sure the value is also not empty.
* @return mixed Returns the field value if there are no errors.
* @throws FieldNotFoundException Throws an exception when the field is not in the array.
* @throws InvalidValueException Throws an exception when the collection isn't an array or the value is empty.
*/
protected static function validateFieldExists(string $field, $collection, string $collectionName = "payload", bool $validateEmpty = true)
{
if (!(is_array($collection) || $collection instanceof \ArrayAccess)) {
throw new InvalidValueException("Invalid array: {$collectionName}");
}
if (!isset($collection[$field])) {
throw new FieldNotFoundException($field, $collectionName);
}
if ($validateEmpty && empty($collection[$field])) {
throw new InvalidValueException("Field cannot be empty: {$collectionName}[{$field}]");
}
return $collection[$field];
}
/**
* Generate the location for an SSO redirect.
*
* @param string $requestJWT
* @return string
*/
public function generateResponseLocation(string $requestJWT) : string
{
// Validate the request token.
$request = $this->jwtDecode($requestJWT);
if ($this->isGuest()) {
$data = [self::FIELD_USER => new \stdClass(), self::FIELD_STATE => $request[self::FIELD_STATE] ?? []];
} else {
// Generate the response token.
$data = [self::FIELD_USER => $this->user, self::FIELD_STATE => $request[self::FIELD_STATE] ?? []];
}
$response = $this->jwtEncode($data);
$location = $request[self::FIELD_REDIRECT_URL] . "#" . http_build_query(["jwt" => $response]);
return $location;
}
/**
* Decode a JWT with the connection's settings.
*
* @param string $jwt
* @return array
*/
public function jwtDecode(string $jwt) : array
{
/**
* @psalm-suppress InvalidArgument
*/
$keys = [];
foreach ($this->keys as $id => $key) {
$keys[$id] = new Key($key, $this->getSigningAlgorithm());
}
$payload = JWT::decode($jwt, $keys);
$payload = $this->stdClassToArray($payload);
return $payload;
}
/**
* Convert an object to an array, recursively.
*
* @param array|object $o
* @return array
*/
protected function stdClassToArray($o) : array
{
if (!is_array($o) && !$o instanceof \stdClass) {
throw new UnexpectedValueException("JsConnect::stdClassToArray() expects an object or array, scalar given.", 400);
}
$o = (array) $o;
$r = [];
foreach ($o as $key => $value) {
if (is_array($value) || is_object($value)) {
$r[$key] = $this->stdClassToArray($value);
} else {
$r[$key] = $value;
}
}
return $r;
}
/**
* Whether or not the user is signed in.
*
* @return bool
*/
public function isGuest() : bool
{
return $this->guest;
}
/**
* Set whether or not the user is signed in.
*
* @param bool $isGuest
* @return $this
*/
public function setGuest(bool $isGuest)
{
$this->guest = $isGuest;
return $this;
}
/**
* Wrap a payload in a JWT.
*
* @param array $payload
* @return string
*/
public function jwtEncode(array $payload) : string
{
$payload += ["v" => $this->getVersion(), "iat" => $this->getTimestamp(), "exp" => $this->getTimestamp() + $this->getTimeout()];
$jwt = JWT::encode($payload, $this->getSigningSecret(), $this->getSigningAlgorithm(), null, [self::FIELD_CLIENT_ID => $this->getSigningClientID()]);
return $jwt;
}
/**
* Get the current timestamp.
*
* This time is used for signing and verifying tokens.
*
* @return int
*/
protected function getTimestamp() : int
{
$r = JWT::$timestamp ?: time();
return $r;
}
/**
* Get the secret that is used to sign JWTs.
*
* @return string
*/
public function getSigningSecret() : string
{
return $this->keys[$this->signingClientID];
}
/**
* Get the algorithm used to sign tokens.
*
* @return string
*/
public function getSigningAlgorithm() : string
{
return $this->signingAlgorithm;
}
/**
* Set the algorithm used to sign tokens.
*
* @param string $signingAlgorithm
* @return $this
*/
public function setSigningAlgorithm(string $signingAlgorithm)
{
if (!in_array($signingAlgorithm, static::ALLOWED_ALGORITHMS)) {
throw new UnexpectedValueException("Algorithm not allowed");
}
$this->signingAlgorithm = $signingAlgorithm;
return $this;
}
/**
* Get the client ID that is used to sign JWTs.
*
* @return string
*/
public function getSigningClientID() : string
{
return $this->signingClientID;
}
/**
* Redirect to a new location.
*
* @param string $location
*/
protected function redirect(string $location) : void
{
header("Location: {$location}", true, 302);
die;
}
/**
* Set the credentials that will be used to sign requests.
*
* @param string $clientID
* @param string $secret
* @return $this
*/
public function setSigningCredentials(string $clientID, string $secret)
{
$this->keys[$clientID] = $secret;
$this->signingClientID = $clientID;
return $this;
}
public function getUser() : array
{
return $this->user;
}
/**
* Set the roles on the user.
*
* @param array $roles
* @return $this
*/
public function setRoles(array $roles)
{
$this->setUserField(self::FIELD_ROLES, $roles);
return $this;
}
/**
* Returns a JWT header.
*
* @param string $jwt
*
* @return array|null
*/
public static final function decodeJWTHeader(string $jwt) : ?array
{
$tks = explode(".", $jwt);
if (count($tks) != 3) {
throw new UnexpectedValueException("Wrong number of segments");
}
list($headb64) = $tks;
if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))) {
throw new UnexpectedValueException("Invalid header encoding");
}
return json_decode(json_encode($header), true);
}
/**
* Get the version used to sign requests.
*
* @return string
*/
public function getVersion() : string
{
return self::VERSION;
}
/**
* Get the JWT expiry timeout.
*
* @return int
*/
public function getTimeout() : int
{
return $this->timeout;
}
/**
* Set the JWT expiry timeout.
*
* @param int $timeout
* @return $this
*/
public function setTimeout(int $timeout)
{
$this->timeout = $timeout;
return $this;
}
}
}
namespace Vanilla\JsConnect\Exceptions {
/**
* The base class for all JsConnect exceptions.
*/
class JsConnectException extends \Exception
{
}
}
namespace Vanilla\JsConnect\Exceptions {
/**
* An exception that represents a missing field in a request or response.
*/
class FieldNotFoundException extends JsConnectException
{
/**
* FieldNotFoundException constructor.
*
* @param string $field
* @param string $collection
*/
public function __construct(string $field, string $collection = "payload")
{
parent::__construct("Missing field: {$collection}[{$field}]", 404);
}
}
}
namespace Vanilla\JsConnect\Exceptions {
/**
* An exception that represents a value that is not the correct type or expected value.
*/
class InvalidValueException extends JsConnectException
{
/**
* InvalidValueException constructor.
*
* @param string $message
*/
public function __construct(string $message = "")
{
parent::__construct($message, 400);
}
}
}
namespace Firebase\JWT {
class BeforeValidException extends \UnexpectedValueException
{
}
}
namespace Firebase\JWT {
class ExpiredException extends \UnexpectedValueException
{
}
}
namespace Firebase\JWT {
use ArrayAccess;
use DateTime;
use DomainException;
use Exception;
use InvalidArgumentException;
use OpenSSLAsymmetricKey;
use OpenSSLCertificate;
use stdClass;
use UnexpectedValueException;
/**
* JSON Web Token implementation, based on this spec:
* https://tools.ietf.org/html/rfc7519
*
* PHP version 5
*
* @category Authentication
* @package Authentication_JWT
* @author Neuman Vong <[email protected]>
* @author Anant Narayanan <[email protected]>
* @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
* @link https://github.com/firebase/php-jwt
*/
class JWT
{
private const ASN1_INTEGER = 0x2;
private const ASN1_SEQUENCE = 0x10;
private const ASN1_BIT_STRING = 0x3;
/**
* When checking nbf, iat or expiration times,
* we want to provide some extra leeway time to
* account for clock skew.
*
* @var int
*/
public static $leeway = 0;
/**
* Allow the current timestamp to be specified.
* Useful for fixing a value within unit testing.
* Will default to PHP time() value if null.
*
* @var ?int
*/
public static $timestamp = null;
/**
* @var array<string, string[]>
*/
public static $supported_algs = ['ES384' => ['openssl', 'SHA384'], 'ES256' => ['openssl', 'SHA256'], 'ES256K' => ['openssl', 'SHA256'], 'HS256' => ['hash_hmac', 'SHA256'], 'HS384' => ['hash_hmac', 'SHA384'], 'HS512' => ['hash_hmac', 'SHA512'], 'RS256' => ['openssl', 'SHA256'], 'RS384' => ['openssl', 'SHA384'], 'RS512' => ['openssl', 'SHA512'], 'EdDSA' => ['sodium_crypto', 'EdDSA']];
/**
* Decodes a JWT string into a PHP object.
*
* @param string $jwt The JWT
* @param Key|array<string,Key> $keyOrKeyArray The Key or associative array of key IDs (kid) to Key objects.
* If the algorithm used is asymmetric, this is the public key
* Each Key object contains an algorithm and matching key.
* Supported algorithms are 'ES384','ES256', 'HS256', 'HS384',
* 'HS512', 'RS256', 'RS384', and 'RS512'
*
* @return stdClass The JWT's payload as a PHP object
*
* @throws InvalidArgumentException Provided key/key-array was empty or malformed
* @throws DomainException Provided JWT is malformed
* @throws UnexpectedValueException Provided JWT was invalid
* @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
* @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
* @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
* @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
*
* @uses jsonDecode
* @uses urlsafeB64Decode
*/
public static function decode(string $jwt, $keyOrKeyArray) : stdClass
{
// Validate JWT
$timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp;
if (empty($keyOrKeyArray)) {
throw new InvalidArgumentException('Key may not be empty');
}
$tks = \explode('.', $jwt);
if (\count($tks) !== 3) {
throw new UnexpectedValueException('Wrong number of segments');
}
list($headb64, $bodyb64, $cryptob64) = $tks;
$headerRaw = static::urlsafeB64Decode($headb64);
if (null === ($header = static::jsonDecode($headerRaw))) {
throw new UnexpectedValueException('Invalid header encoding');
}
$payloadRaw = static::urlsafeB64Decode($bodyb64);
if (null === ($payload = static::jsonDecode($payloadRaw))) {
throw new UnexpectedValueException('Invalid claims encoding');
}
if (\is_array($payload)) {
// prevent PHP Fatal Error in edge-cases when payload is empty array
$payload = (object) $payload;
}
if (!$payload instanceof stdClass) {
throw new UnexpectedValueException('Payload must be a JSON object');
}
$sig = static::urlsafeB64Decode($cryptob64);
if (empty($header->alg)) {
throw new UnexpectedValueException('Empty algorithm');
}
if (empty(static::$supported_algs[$header->alg])) {
throw new UnexpectedValueException('Algorithm not supported');
}
$key = self::getKey($keyOrKeyArray, property_exists($header, 'kid') ? $header->kid : null);
// Check the algorithm
if (!self::constantTimeEquals($key->getAlgorithm(), $header->alg)) {
// See issue #351
throw new UnexpectedValueException('Incorrect key for this algorithm');
}
if (\in_array($header->alg, ['ES256', 'ES256K', 'ES384'], true)) {
// OpenSSL expects an ASN.1 DER sequence for ES256/ES256K/ES384 signatures
$sig = self::signatureToDER($sig);
}
if (!self::verify("{$headb64}.{$bodyb64}", $sig, $key->getKeyMaterial(), $header->alg)) {
throw new SignatureInvalidException('Signature verification failed');
}
// Check the nbf if it is defined. This is the time that the
// token can actually be used. If it's not yet that time, abort.
if (isset($payload->nbf) && $payload->nbf > $timestamp + static::$leeway) {
throw new BeforeValidException('Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->nbf));
}
// Check that this token has been created before 'now'. This prevents
// using tokens that have been created for later use (and haven't
// correctly used the nbf claim).
if (isset($payload->iat) && $payload->iat > $timestamp + static::$leeway) {
throw new BeforeValidException('Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->iat));
}
// Check if this token has expired.
if (isset($payload->exp) && $timestamp - static::$leeway >= $payload->exp) {
throw new ExpiredException('Expired token');
}
return $payload;
}
/**
* Converts and signs a PHP array into a JWT string.
*
* @param array<mixed> $payload PHP array
* @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
* @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256',
* 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
* @param string $keyId
* @param array<string, string> $head An array with header elements to attach
*
* @return string A signed JWT
*
* @uses jsonEncode
* @uses urlsafeB64Encode
*/
public static function encode(array $payload, $key, string $alg, string $keyId = null, array $head = null) : string
{
$header = ['typ' => 'JWT', 'alg' => $alg];
if ($keyId !== null) {
$header['kid'] = $keyId;
}
if (isset($head) && \is_array($head)) {
$header = \array_merge($head, $header);
}
$segments = [];
$segments[] = static::urlsafeB64Encode((string) static::jsonEncode($header));
$segments[] = static::urlsafeB64Encode((string) static::jsonEncode($payload));
$signing_input = \implode('.', $segments);
$signature = static::sign($signing_input, $key, $alg);
$segments[] = static::urlsafeB64Encode($signature);
return \implode('.', $segments);
}
/**
* Sign a string with a given key and algorithm.
*
* @param string $msg The message to sign
* @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
* @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256',
* 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
*
* @return string An encrypted message
*
* @throws DomainException Unsupported algorithm or bad key was specified
*/
public static function sign(string $msg, $key, string $alg) : string
{
if (empty(static::$supported_algs[$alg])) {
throw new DomainException('Algorithm not supported');
}
list($function, $algorithm) = static::$supported_algs[$alg];
switch ($function) {
case 'hash_hmac':
if (!\is_string($key)) {
throw new InvalidArgumentException('key must be a string when using hmac');
}
return \hash_hmac($algorithm, $msg, $key, true);
case 'openssl':
$signature = '';
$success = \openssl_sign($msg, $signature, $key, $algorithm);
// @phpstan-ignore-line
if (!$success) {
throw new DomainException('OpenSSL unable to sign data');
}
if ($alg === 'ES256' || $alg === 'ES256K') {
$signature = self::signatureFromDER($signature, 256);
} elseif ($alg === 'ES384') {
$signature = self::signatureFromDER($signature, 384);
}
return $signature;
case 'sodium_crypto':
if (!\function_exists('sodium_crypto_sign_detached')) {
throw new DomainException('libsodium is not available');
}
if (!\is_string($key)) {
throw new InvalidArgumentException('key must be a string when using EdDSA');
}
try {
// The last non-empty line is used as the key.
$lines = array_filter(explode("\n", $key));
$key = base64_decode((string) end($lines));
if (\strlen($key) === 0) {
throw new DomainException('Key cannot be empty string');
}
return sodium_crypto_sign_detached($msg, $key);
} catch (Exception $e) {
throw new DomainException($e->getMessage(), 0, $e);
}
}
throw new DomainException('Algorithm not supported');
}
/**
* Verify a signature with the message, key and method. Not all methods
* are symmetric, so we must have a separate verify and sign method.
*
* @param string $msg The original message (header and body)
* @param string $signature The original signature
* @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial For HS*, a string key works. for RS*, must be an instance of OpenSSLAsymmetricKey
* @param string $alg The algorithm
*
* @return bool
*
* @throws DomainException Invalid Algorithm, bad key, or OpenSSL failure
*/
private static function verify(string $msg, string $signature, $keyMaterial, string $alg) : bool
{
if (empty(static::$supported_algs[$alg])) {
throw new DomainException('Algorithm not supported');
}
list($function, $algorithm) = static::$supported_algs[$alg];
switch ($function) {
case 'openssl':
$success = \openssl_verify($msg, $signature, $keyMaterial, $algorithm);
// @phpstan-ignore-line
if ($success === 1) {
return true;
}
if ($success === 0) {
return false;
}
// returns 1 on success, 0 on failure, -1 on error.
throw new DomainException('OpenSSL error: ' . \openssl_error_string());
case 'sodium_crypto':
if (!\function_exists('sodium_crypto_sign_verify_detached')) {
throw new DomainException('libsodium is not available');
}
if (!\is_string($keyMaterial)) {
throw new InvalidArgumentException('key must be a string when using EdDSA');
}
try {
// The last non-empty line is used as the key.
$lines = array_filter(explode("\n", $keyMaterial));
$key = base64_decode((string) end($lines));
if (\strlen($key) === 0) {
throw new DomainException('Key cannot be empty string');
}
if (\strlen($signature) === 0) {
throw new DomainException('Signature cannot be empty string');
}
return sodium_crypto_sign_verify_detached($signature, $msg, $key);
} catch (Exception $e) {
throw new DomainException($e->getMessage(), 0, $e);
}
case 'hash_hmac':
default:
if (!\is_string($keyMaterial)) {
throw new InvalidArgumentException('key must be a string when using hmac');
}
$hash = \hash_hmac($algorithm, $msg, $keyMaterial, true);
return self::constantTimeEquals($hash, $signature);
}
}
/**
* Decode a JSON string into a PHP object.
*
* @param string $input JSON string
*
* @return mixed The decoded JSON string
*
* @throws DomainException Provided string was invalid JSON
*/
public static function jsonDecode(string $input)
{
$obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
if ($errno = \json_last_error()) {
self::handleJsonError($errno);
} elseif ($obj === null && $input !== 'null') {
throw new DomainException('Null result with non-null input');
}
return $obj;
}
/**
* Encode a PHP array into a JSON string.
*
* @param array<mixed> $input A PHP array
*
* @return string JSON representation of the PHP array
*
* @throws DomainException Provided object could not be encoded to valid JSON
*/
public static function jsonEncode(array $input) : string
{
if (PHP_VERSION_ID >= 50400) {