1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace IonGhitun\JwtToken\Tests; |
5
|
|
|
|
6
|
|
|
use Carbon\Carbon; |
7
|
|
|
use IonGhitun\JwtToken\Exceptions\JwtException; |
8
|
|
|
use IonGhitun\JwtToken\Jwt; |
9
|
|
|
use PHPUnit\Framework\TestCase; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class JtwTest |
13
|
|
|
* |
14
|
|
|
* @package IonGhitun\JwtToken\Tests |
15
|
|
|
*/ |
16
|
|
|
class JtwTest extends TestCase |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* Test generate and validate token |
20
|
|
|
* |
21
|
|
|
* @throws JwtException |
22
|
|
|
*/ |
23
|
|
|
public function testGenerateToken() |
24
|
|
|
{ |
25
|
|
|
$token = Jwt::generateToken(['test' => 'phpunit']); |
26
|
|
|
|
27
|
|
|
$this->assertArrayHasKey('test', Jwt::validateToken($token)); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Test not valid jwt token |
32
|
|
|
* |
33
|
|
|
* @throws JwtException |
34
|
|
|
*/ |
35
|
|
|
public function testJwtException() |
36
|
|
|
{ |
37
|
|
|
$this->expectException(JwtException::class); |
38
|
|
|
|
39
|
|
|
Jwt::validateToken('token'); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Test not valid jwt token header or payload |
44
|
|
|
* |
45
|
|
|
* @throws JwtException |
46
|
|
|
*/ |
47
|
|
|
public function testJwtExceptionBadToken() |
48
|
|
|
{ |
49
|
|
|
$this->expectException(JwtException::class); |
50
|
|
|
|
51
|
|
|
Jwt::validateToken('token.token.token'); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Test jwt token expired |
56
|
|
|
* |
57
|
|
|
* @throws JwtException |
58
|
|
|
*/ |
59
|
|
|
public function testJwtExceptionExpired() |
60
|
|
|
{ |
61
|
|
|
$this->expectException(JwtException::class); |
62
|
|
|
|
63
|
|
|
$payload = ['test' => 'phpunit', 'expiration' => Carbon::now()->subDay()->format('Y-m-d H:i:s')]; |
64
|
|
|
|
65
|
|
|
$token = Jwt::generateToken($payload); |
66
|
|
|
|
67
|
|
|
Jwt::validateToken($token); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Test jwt token invalid signature |
72
|
|
|
* |
73
|
|
|
* @throws JwtException |
74
|
|
|
*/ |
75
|
|
|
public function testJwtExceptionInvalidSignature() |
76
|
|
|
{ |
77
|
|
|
$this->expectException(JwtException::class); |
78
|
|
|
|
79
|
|
|
$payload = ['test' => 'phpunit', 'expiration' => Carbon::now()->addDay()->format('Y-m-d H:i:s')]; |
80
|
|
|
|
81
|
|
|
$token = Jwt::generateToken($payload); |
82
|
|
|
|
83
|
|
|
$invalidTokenArray = explode('.', $token); |
84
|
|
|
|
85
|
|
|
Jwt::validateToken($invalidTokenArray[0] . '.' . $invalidTokenArray[1] . '.' . 'signature'); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|