|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Milwad\LaravelValidate\Rules; |
| 4 | + |
| 5 | +use Illuminate\Contracts\Validation\Rule; |
| 6 | + |
| 7 | +class ValidJwt implements Rule |
| 8 | +{ |
| 9 | + /** |
| 10 | + * Check jwt is valid. |
| 11 | + * |
| 12 | + * @param string $attribute |
| 13 | + * @param mixed $value |
| 14 | + * @return bool |
| 15 | + * @throws \JsonException |
| 16 | + */ |
| 17 | + public function passes($attribute, $value) |
| 18 | + { |
| 19 | + $tokenParts = explode('.', $value); |
| 20 | + $header = base64_decode($tokenParts[0]); |
| 21 | + $payload = base64_decode($tokenParts[1]); |
| 22 | + $signature_provided = $tokenParts[2]; |
| 23 | + |
| 24 | + // check the expiration time - note this will cause an error if there is no 'exp' claim in the jwt |
| 25 | + $expiration = json_decode($payload, false, 512, JSON_THROW_ON_ERROR)->exp; |
| 26 | + $is_token_expired = ($expiration - time()) < 0; |
| 27 | + |
| 28 | + // build a signature based on the header and payload using the secret |
| 29 | + $base64_url_header = $this->base64url_encode($header); |
| 30 | + $base64_url_payload = $this->base64url_encode($payload); |
| 31 | + $signature = hash_hmac('SHA256', $base64_url_header . "." . $base64_url_payload, 'secret', true); |
| 32 | + $base64_url_signature = $this->base64url_encode($signature); |
| 33 | + |
| 34 | + // verify it matches the signature provided in the jwt |
| 35 | + $is_signature_valid = ($base64_url_signature === $signature_provided); |
| 36 | + |
| 37 | + return !($is_token_expired || !$is_signature_valid); |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Get the validation error message. |
| 42 | + * |
| 43 | + * @return string |
| 44 | + */ |
| 45 | + public function message() |
| 46 | + { |
| 47 | + return __('jwt'); |
| 48 | + } |
| 49 | + |
| 50 | + private function base64url_encode($str) |
| 51 | + { |
| 52 | + return rtrim(strtr(base64_encode($str), '+/', '-_'), '='); |
| 53 | + } |
| 54 | +} |
0 commit comments