-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.php
74 lines (57 loc) · 2.49 KB
/
jwt.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
define('TOKEN_EXPIRED', 'ERR_TOKEN_EXPIRED');
define('TOKEN_INVALID', 'ERR_TOKEN_INVALID');
define('TOKEN_VALID', 'TOKEN_VALID');
function generate_token($payload, $expiry, $secret) {
$header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
$payload['exp'] = $expiry;
$payload = json_encode($payload);
$base64_header = rtrim(base64_encode($header), '=');
$base64_payload = rtrim(base64_encode($payload), '=');
$signature = hash_hmac('sha256', $base64_header . "." . $base64_payload, $secret, true);
$base64_signature = rtrim(base64_encode($signature), '=');
$jwt = $base64_header . "." . $base64_payload . "." . $base64_signature;
return $jwt;
}
function validate_token($token, $secret) {
$data = explode('.', $token);
$base64_header = $data[0];
$base64_payload = $data[1];
$base64_signature = $data[2];
$header = base64_decode($base64_header);
$payload = base64_decode($base64_payload);
$payload_array = json_decode($payload, true);
$token_expiry = $payload_array['exp'];
if(time() > $token_expiry) {
return TOKEN_EXPIRED;
}
$signature = base64_decode($base64_signature);
$expected_signature = hash_hmac('sha256', $base64_header . "." . $base64_payload, $secret, true);
$is_valid = hash_equals($expected_signature, $signature);
if ($is_valid) {
return TOKEN_VALID;
} else {
return TOKEN_INVALID;
}
}
function validate_token_with_payload($token, $secret) {
$data = explode('.', $token);
$base64_header = $data[0];
$base64_payload = $data[1];
$base64_signature = $data[2];
$header = base64_decode($base64_header);
$payload = base64_decode($base64_payload);
$payload_array = json_decode($payload, true);
$token_expiry = $payload_array['exp'];
if(time() > $token_expiry) {
return TOKEN_EXPIRED;
}
$signature = base64_decode($base64_signature);
$expected_signature = hash_hmac('sha256', $base64_header . "." . $base64_payload, $secret, true);
$is_valid = hash_equals($expected_signature, $signature);
if ($is_valid) {
return $payload_array;
} else {
return TOKEN_INVALID;
}
}