-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJwt.php
More file actions
219 lines (188 loc) · 5.74 KB
/
Jwt.php
File metadata and controls
219 lines (188 loc) · 5.74 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
<?php
/**
* This file is part of Blitz PHP framework.
*
* (c) 2022 Dimitri Sitchet Tomkeu <devcode.dst@gmail.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace BlitzPHP\Utilities;
use Exception;
use Firebase\JWT\JWT as Firebase;
use Firebase\JWT\Key;
use Throwable;
/**
* Utilitaires de manipulation de token JWT (JSON Web Token)
*/
class Jwt
{
/**
* Configuration JWT
*
* @var array
*/
private $config;
/**
* Instance singleton de la classe
*
* @var self|null
*/
private static $_instance;
/**
* Constructeur
*
* @param array $config Configuration JWT
*/
public function __construct(array $config = [])
{
$this->config = array_merge([
'key' => 'blitz-php-jwt-key',
'exp_time' => 5, // 5 minutes
'merge' => false,
'algorithm' => 'HS256',
'base_url' => Helpers::findBaseUrl(),
], $config);
$this->config['public_key'] ??= $this->config['key'];
}
/**
* Récupère l'instance singleton
*
* @param array $config Configuration JWT (si création de nouvelle instance)
*/
public static function instance(array $config = []): self
{
if (null === static::$_instance) {
static::$_instance = new static($config);
}
return static::$_instance;
}
/**
* Retourne les configurations JWT appropriées
*
* @param array $config Configuration additionnelle
*
* @return object Configuration JWT sous forme d'objet
*/
private static function config(array $config = []): object
{
return (object) array_merge(self::instance()->config, $config);
}
/**
* Génère un token JWT d'authentification
*
* @param array $data Données à inclure dans le token
* @param array $config Configuration spécifique pour cet encodage
*
* @return string Token JWT encodé
*
* @throws Exception Si l'encodage échoue
*/
public static function encode(array $data = [], array $config = []): string
{
$config = self::config($config);
$payload = [
'iat' => time(),
'iss' => $config->base_url,
'exp' => time() + (60 * $config->exp_time),
];
if ($config->merge !== true) {
$payload['data'] = $data;
} else {
$payload = array_merge($payload, $data);
}
try {
return Firebase::encode($payload, $config->key, $config->algorithm);
} catch (Throwable $e) {
throw new Exception('JWT Exception : ' . $e->getMessage(), 0, $e);
}
}
/**
* Récupère le payload du token d'entrée
*
* @param bool $full Si true, retourne le payload complet avec les métadonnées
* @param array $config Configuration spécifique pour la décodage
*
* @return mixed Données du payload
*
* @throws Exception Si le token n'est pas trouvé ou est invalide
*/
public static function payload(bool $full = false, array $config = [])
{
$token = self::getToken();
$config = self::config($config);
if (empty($token)) {
throw new Exception('Access token not found.');
}
$payload = self::decode($token, (array) $config);
$returned = $payload;
if ($config->merge !== true) {
$returned = $payload->data ?? $payload;
}
if (! $full) {
unset($returned->iat, $returned->iss, $returned->exp);
}
return $returned;
}
/**
* Décode un token JWT d'authentification
*
* @param string $token Token JWT à décoder
* @param array $config Configuration spécifique pour le décodage
*
* @return object Payload décodé
*
* @throws Exception Si le décodage échoue
*/
public static function decode(string $token, array $config = []): object
{
$config = self::config($config);
try {
return Firebase::decode(
$token,
new Key($config->public_key, $config->algorithm)
);
} catch (Throwable $e) {
throw new Exception('JWT Exception : ' . $e->getMessage(), 0, $e);
}
}
/**
* Récupère le token d'accès à partir des headers HTTP
*
* @return string|null Token JWT ou null si non trouvé
*/
public static function getToken(): ?string
{
$authorization = self::getAuthorization();
if (! empty($authorization) && preg_match('/Bearer\s(\S+)/', $authorization, $matches)) {
return $matches[1];
}
return null;
}
/**
* Récupère le header "Authorization" de la requête HTTP
*
* @return string|null Contenu du header Authorization ou null si non présent
*/
public static function getAuthorization(): ?string
{
if (isset($_SERVER['Authorization'])) {
return trim($_SERVER['Authorization']);
}
if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
// Nginx ou fast CGI
return trim($_SERVER['HTTP_AUTHORIZATION']);
}
if (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
$requestHeaders = array_combine(
array_map('ucwords', array_keys($requestHeaders)),
array_values(($requestHeaders))
);
if (isset($requestHeaders['Authorization'])) {
return trim($requestHeaders['Authorization']);
}
}
return null;
}
}