| @@ -75,9 +75,12 @@ | ||
| 75 | 75 | $signature = $this->base64Decode($signature64); |
| 76 | 76 | if (!$signature) { |
| 77 | 77 | throw new Exception('Invalid JWT Signature'); |
| 78 | 78 | |
| 79 | - } elseif ($payloadJson = $this->base64Decode($payload64)) { | |
| 79 | + } | |
| 80 | + | |
| 81 | + $payloadJson = $this->base64Decode($payload64); | |
| 82 | + if ($payloadJson) { | |
| 80 | 83 | $hash = hash_hmac($this->algorithm, "{$header64}.{$payload64}", $secret, true); |
| 81 | 84 | if (hash_equals($hash, $signature)) { |
| 82 | 85 | $payload = $this->jsonDecode($payloadJson); |
| 83 | 86 | if (empty($payload->exp) == false && $payload->exp < time()) { |
| @@ -112,10 +115,14 @@ | ||
| 112 | 115 | throw new Exception('Invalid Hash Algorithm'); |
| 113 | 116 | } |
| 114 | 117 | |
| 115 | 118 | /** |
| 116 | - * Base64 encoding that is url safe | |
| 119 | + * Base64url encode JWT segments. | |
| 117 | 120 | * |
| 121 | + * JWT compact serialization requires base64url encoding for the header, | |
| 122 | + * payload, and binary signature. This is protocol encoding, not | |
| 123 | + * obfuscation. | |
| 124 | + * | |
| 118 | 125 | * @param string $input |
| 119 | 126 | * |
| 120 | 127 | * @return string |
| 121 | 128 | */ |
| @@ -124,8 +131,9 @@ | ||
| 124 | 131 | return str_replace( |
| 125 | 132 | '=', |
| 126 | 133 | '', |
| 127 | 134 | strtr( |
| 135 | + // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- JWT base64url encoding requires Base64. | |
| 128 | 136 | base64_encode($input), |
| 129 | 137 | '+/', |
| 130 | 138 | '-_' |
| 131 | 139 | ) |
| @@ -132,10 +140,14 @@ | ||
| 132 | 140 | ); |
| 133 | 141 | } |
| 134 | 142 | |
| 135 | 143 | /** |
| 136 | - * Restore URL safe base64 string | |
| 144 | + * Base64url decode JWT segments. | |
| 137 | 145 | * |
| 146 | + * JWT compact serialization stores header, payload, and signature as | |
| 147 | + * base64url. Strict Base64 decoding is required after translating the URL | |
| 148 | + * safe alphabet. | |
| 149 | + * | |
| 138 | 150 | * @param string $input |
| 139 | 151 | * |
| 140 | 152 | * @return string |
| 141 | 153 | */ |
| @@ -146,9 +158,12 @@ | ||
| 146 | 158 | $padding = 4 - $remainder; |
| 147 | 159 | $input .= str_repeat('=', $padding); |
| 148 | 160 | } |
| 149 | 161 | |
| 150 | - return base64_decode(strtr($input, '-_', '+/')); | |
| 162 | + // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- JWT base64url decoding requires Base64 with strict mode enabled. | |
| 163 | + $decoded = base64_decode(strtr($input, '-_', '+/'), true); | |
| 164 | + | |
| 165 | + return false === $decoded ? '' : $decoded; | |
| 151 | 166 | } |
| 152 | 167 | |
| 153 | 168 | /** |
| 154 | 169 | * JSON Encode without escape characters |