1
+ <?php
2
+
3
+ namespace PKP \core ;
4
+
5
+ use stdClass ;
6
+ use Firebase \JWT \JWT ;
7
+ use PKP \config \Config ;
8
+ use UnexpectedValueException ;
9
+
10
+ class PKPJwt extends JWT
11
+ {
12
+ /**
13
+ * Decodes a JWT string into a PHP object.
14
+ *
15
+ * @param string $jwt The JWT
16
+ * @param Key|ArrayAccess<string,Key>|array<string,Key> $keyOrKeyArray The Key or associative array of key IDs
17
+ * (kid) to Key objects.
18
+ * If the algorithm used is asymmetric, this is
19
+ * the public key.
20
+ * Each Key object contains an algorithm and
21
+ * matching key.
22
+ * Supported algorithms are 'ES384','ES256',
23
+ * 'HS256', 'HS384', 'HS512', 'RS256', 'RS384'
24
+ * and 'RS512'.
25
+ * @param stdClass $headers Optional. Populates stdClass with headers.
26
+ *
27
+ * @return stdClass The JWT's payload as a PHP object
28
+ *
29
+ * @throws InvalidArgumentException Provided key/key-array was empty or malformed
30
+ * @throws DomainException Provided JWT is malformed
31
+ * @throws UnexpectedValueException Provided JWT was invalid
32
+ * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
33
+ * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
34
+ * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
35
+ * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
36
+ *
37
+ * @uses jsonDecode
38
+ * @uses urlsafeB64Decode
39
+ */
40
+ public static function decode (string $ jwt , $ keyOrKeyArray , stdClass &$ headers = null ): stdClass
41
+ {
42
+ $ tks = explode ('. ' , $ jwt );
43
+
44
+ if (count ($ tks ) !== 3 ) {
45
+ throw new UnexpectedValueException ('Wrong number of segments ' );
46
+ }
47
+
48
+ list ($ headb64 , $ bodyb64 , $ cryptob64 ) = $ tks ;
49
+
50
+ $ payloadRaw = static ::urlsafeB64Decode ($ bodyb64 );
51
+
52
+ if (null === ($ payload = static ::jsonDecode ($ payloadRaw ))) {
53
+ throw new UnexpectedValueException ('Invalid claims encoding ' );
54
+ }
55
+
56
+ if (is_array ($ payload )) {
57
+ return parent ::decode ($ jwt , $ keyOrKeyArray , $ headers );
58
+ }
59
+
60
+ if (is_string ($ payload )) {
61
+ return parent ::decode (
62
+ static ::encode (
63
+ [$ payload ],
64
+ Config::getVar ('security ' , 'api_key_secret ' , '' ),
65
+ 'HS256 '
66
+ ),
67
+ $ keyOrKeyArray ,
68
+ $ headers
69
+ );
70
+ }
71
+
72
+ return parent ::decode ($ jwt , $ keyOrKeyArray , $ headers );
73
+ }
74
+ }
0 commit comments