· 7 years ago · Sep 13, 2018, 09:44 PM
1<?php
2
3class JWT {
4
5 /**
6 * Generate new JWT
7 */
8 public static function sign($payloadData, $secretKey, $options = [])
9 {
10 // Create token header as a JSON string
11 $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
12
13 // Create token payload as a JSON string
14 if (isset($options['expiresIn']))
15 {
16 $payloadData['exp'] = time() + $options['expiresIn'];
17 }
18
19 $payload = json_encode($payloadData);
20
21 // Encode Header to Base64Url String
22 $base64UrlHeader = str_replace(
23 ['+', '/', '='],
24 ['-', '_', ''],
25 base64_encode($header)
26 );
27
28 // Encode Payload to Base64Url String
29 $base64UrlPayload = str_replace(
30 ['+', '/', '='],
31 ['-', '_', ''],
32 base64_encode($payload)
33 );
34
35 // Create Signature Hash
36 $signature = hash_hmac(
37 'sha256',
38 $base64UrlHeader . "." . $base64UrlPayload,
39 $secretKey,
40 true
41 );
42
43 // Encode Signature to Base64Url String
44 $base64UrlSignature = str_replace(
45 ['+', '/', '='],
46 ['-', '_', ''],
47 base64_encode($signature)
48 );
49
50 // Create JWT
51 $jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
52
53 return $jwt;
54 }
55
56 /**
57 * Verify provided JWT
58 */
59 public static function verify($token, $secretKey)
60 {
61 if (!preg_match('/^[\w\-]+\.[\w\-]+\.[\w\-]+$/', $token))
62 {
63 return false;
64 }
65
66 list($header, $payload, $signature) = explode('.', $token);
67
68 $verifySignature = hash_hmac(
69 'sha256',
70 $header . "." . $payload,
71 $secretKey,
72 true
73 );
74 $verifySignature = str_replace(
75 ['+', '/', '='],
76 ['-', '_', ''],
77 base64_encode($verifySignature)
78 );
79
80 if ($verifySignature !== $signature)
81 {
82 return false;
83 }
84
85 $decodedPayload = json_decode(base64_decode($payload), true);
86
87 if (isset($decodedPayload['exp']))
88 {
89 if (+$decodedPayload['exp'] < +time())
90 {
91 return false;
92 }
93
94 unset($decodedPayload['exp']);
95 }
96
97 return $decodedPayload;
98 }
99}