Skip to content

Commit 905b13b

Browse files
committed
add valid jwt rule
1 parent 8e35c56 commit 905b13b

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
}
2020
],
2121
"require": {
22-
"laravel/framework": "^8.0|^9.0"
22+
"laravel/framework": "^8.0|^9.0",
2323
},
2424
"require-dev": {
2525
"orchestra/testbench": "^5.0|^6.0|^7.0",

src/Rules/ValidJwt.php

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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

Comments
 (0)