Skip to content

Commit 1b97342

Browse files
committed
add jwt_is_valid with fix
1 parent 25e0c17 commit 1b97342

File tree

3 files changed

+19
-21
lines changed

3 files changed

+19
-21
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: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -12,29 +12,10 @@ class ValidJwt implements Rule
1212
* @param string $attribute
1313
* @param mixed $value
1414
* @return bool
15-
* @throws \JsonException
1615
*/
1716
public function passes($attribute, $value)
1817
{
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);
18+
return preg_match('/^[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$/', $value);
3819
}
3920

4021
/**

tests/ValidJwtTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace Milwad\LaravelValidate\Tests;
44

5+
use Milwad\LaravelValidate\Rules\ValidJwt;
6+
57
class ValidJwtTest extends BaseTest
68
{
79
/**
@@ -13,4 +15,19 @@ protected function setUp(): void
1315
{
1416
parent::setUp();
1517
}
18+
19+
/**
20+
* Test jwt is valid.
21+
*
22+
* @test
23+
* @return void
24+
*/
25+
public function jwt_is_valid()
26+
{
27+
$rules = ['jwt' => [new ValidJwt()]];
28+
$data = ['jwt' => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEyMzQ1Njc4OTAiLCJuYW1lIjoiSm9obiBEb2UiLCJhZG1pbiI6dHJ1ZSwiZXhwIjoxNTgyNjE2MDA1fQ.umEYVDP_kZJGCI3tkU9dmq7CIumEU8Zvftc-klp-334'];
29+
$passes = $this->app['validator']->make($data, $rules)->passes();
30+
31+
$this->assertTrue($passes);
32+
}
1633
}

0 commit comments

Comments
 (0)