@@ -11,7 +11,14 @@ class JwtAuthMiddleware extends Middleware
11
11
{
12
12
private function getVerifiedClaims (String $ token , int $ time , int $ leeway , int $ ttl , String $ secret , array $ requirements ): array
13
13
{
14
- $ algorithms = array ('HS256 ' => 'sha256 ' , 'HS384 ' => 'sha384 ' , 'HS512 ' => 'sha512 ' );
14
+ $ algorithms = array (
15
+ 'HS256 ' => 'sha256 ' ,
16
+ 'HS384 ' => 'sha384 ' ,
17
+ 'HS512 ' => 'sha512 ' ,
18
+ 'RS256 ' => 'sha256 ' ,
19
+ 'RS384 ' => 'sha384 ' ,
20
+ 'RS512 ' => 'sha512 ' ,
21
+ );
15
22
$ token = explode ('. ' , $ token );
16
23
if (count ($ token ) < 3 ) {
17
24
return array ();
@@ -27,22 +34,38 @@ private function getVerifiedClaims(String $token, int $time, int $leeway, int $t
27
34
if (!isset ($ algorithms [$ algorithm ])) {
28
35
return array ();
29
36
}
30
- $ hmac = $ algorithms [$ algorithm ];
31
- $ signature = bin2hex (base64_decode (strtr ($ token [2 ], '-_ ' , '+/ ' )));
32
- if ($ signature != hash_hmac ($ hmac , "$ token [0 ]. $ token [1 ]" , $ secret )) {
37
+ if (!in_array ($ algorithm , $ requirements ['alg ' ])) {
33
38
return array ();
34
39
}
40
+ $ hmac = $ algorithms [$ algorithm ];
41
+ $ signature = base64_decode (strtr ($ token [2 ], '-_ ' , '+/ ' ));
42
+ $ data = "$ token [0 ]. $ token [1 ]" ;
43
+ switch ($ algorithm [0 ]) {
44
+ case 'H ' :
45
+ $ hash = hash_hmac ($ hmac , $ data , $ secret , true );
46
+ if (function_exists ('hash_equals ' )) {
47
+ $ equals = hash_equals ($ signature , $ hash );
48
+ } else {
49
+ $ equals = $ signature == $ hash ;
50
+ }
51
+ if (!$ equals ) {
52
+ return array ();
53
+ }
54
+ break ;
55
+ case 'R ' :
56
+ $ equals = openssl_verify ($ data , $ signature , $ secret , $ hmac ) == 1 ;
57
+ if (!$ equals ) {
58
+ return array ();
59
+ }
60
+ break ;
61
+ }
35
62
$ claims = json_decode (base64_decode (strtr ($ token [1 ], '-_ ' , '+/ ' )), true );
36
63
if (!$ claims ) {
37
64
return array ();
38
65
}
39
66
foreach ($ requirements as $ field => $ values ) {
40
67
if (!empty ($ values )) {
41
- if ($ field == 'alg ' ) {
42
- if (!isset ($ header [$ field ]) || !in_array ($ header [$ field ], $ values )) {
43
- return array ();
44
- }
45
- } else {
68
+ if ($ field != 'alg ' ) {
46
69
if (!isset ($ claims [$ field ]) || !in_array ($ claims [$ field ], $ values )) {
47
70
return array ();
48
71
}
0 commit comments