-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuth.php
More file actions
382 lines (336 loc) · 8.7 KB
/
Auth.php
File metadata and controls
382 lines (336 loc) · 8.7 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
<?php
/**
* Author: Yejia
* Email: ye91@foxmail.com
*/
namespace Cium\ApiAuth;
use Cium\ApiAuth\Exceptions\AccessKeyException;
use Cium\ApiAuth\Exceptions\InvalidTokenException;
use Cium\ApiAuth\Exceptions\SignatureMethodException;
use Cium\ApiAuth\Signatures\SignatureInterface;
/*
const access_key = '{access_key}'; // 服务端生成的 access_key
const secret_key = '{secret_key}'; // 服务端生成的 secret_key
const timestamp = Date.parse(new Date()) / 1000; // 取时间戳
const rand_str = 'asldjaksdjlkjgqpojg64131321'; // 随机字符串自行生成
const header = Base64.encode(JSON.stringify({
"alg": "md5",
}));
const payload = Base64.encode(JSON.stringify({
"timestamp": timestamp,
"rand_str": rand_str,
"access_key": access_key
"body": data,
}));
const signature_string = header + '.' + payload;
function md5Sign(string, secret){
return md5(string + secret);
}
const sign = signature_string + '.' + md5Sign(signature_string,secret_key);
const requestConfig = {
headers: {
"api-sign": sign
}
};
$.post('/api/example',{},requestConfig).then(res=>{
});
*/
/**
* Class Auth
*
* @package Cium\ApiAuth
*/
class Auth
{
//状态开
const STATUS_ON = 'on';
//状态关
const STATUS_OFF = 'off';
/**
* 状态
*
* @var string
*/
private $status = self::STATUS_ON;
/**
* 规则
*
* @var array
*/
private $roles = [];
/**
* 签名方法
*
* @var array
*/
private $signatureMethods = [];
/**
* 忽略
*
* @var array
*/
private $skip = [];
/**
* 超时时间(秒)
*
* @var int
*/
private $timeout = 60;
/**
* Auth constructor.
*
* @param array $config 配置
*/
public function __construct(array $config = [])
{
if (isset($config['status'])) {
$this->status = strval($config['status']);
}
if (isset($config['roles']) && is_array($config['roles'])) {
$this->roles = $config['roles'];
}
if (isset($config['signature_methods']) && is_array($config['signature_methods'])) {
$this->signatureMethods = $config['signature_methods'];
}
if (isset($config['skip']) && is_array($config['skip'])) {
$this->skip = $config['skip'];
}
if (isset($config['timeout'])) {
$this->timeout = intval($config['timeout']);
}
}
/**
* 设置状态
*
* @param string $status
*
* @return $this
*/
public function setStatus(string $status)
{
$this->status = $status;
return $this;
}
/**
* 获取状态
*
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* 设置超时
*
* @param int $time
*
* @return $this
*/
public function setTimeout(int $time)
{
$this->timeout = $time;
return $this;
}
/**
* 获取超时
*
* @return int
*/
public function getTimeout()
{
return $this->timeout;
}
/**
* 设置规则
*
* @param array $roles
*
* @return $this
*/
public function setRoles(array $roles)
{
$this->roles = $roles;
return $this;
}
/**
* 获取规则
*
* @return array
*/
public function getRoles()
{
return $this->roles;
}
/**
* 设置签名方法
*
* @param array $methods
*
* @return $this
*/
public function setSignatureMethods(array $methods)
{
$this->signatureMethods = $methods;
return $this;
}
/**
* 获取签名方法
*
* @return array
*/
public function getSignatureMethods()
{
return $this->signatureMethods;
}
/**
* 设置忽略
*
* @param array $skip
*
* @return $this
*/
public function setSkip(array $skip)
{
$this->skip = $skip;
return $this;
}
/**
* 获取忽略
*
* @return array
*/
public function getSkip()
{
return $this->skip;
}
/**
* 校验
*
* @param string $url
* @param string $token
* @param string $dataStr
*
* @return bool
* @throws AccessKeyException
* @throws InvalidTokenException
* @throws SignatureMethodException
*/
public function check(string $url, string $token, string $dataStr)
{
if ($this->status == self::STATUS_ON && !$this->isSkip($url)) {
if (mb_substr_count($token, '.') != 2) {
throw new InvalidTokenException("Sign format error");
}
list($headerStr, $payloadStr, $signature) = explode(".", $token);
list($header, $payload, $alg) = $this->parseParams($headerStr, $payloadStr);
$role = $this->roles[$payload['access_key']];
$this->dataCheck($alg, $payload['data'], $dataStr);
$this->signatureCheck($alg, "$headerStr.$payloadStr", $role['secret_key'], $signature);
return $role['name'];
}
return false;
}
/**
* 检查忽略
*
* @param string $url
*
* @return mixed
*/
private function isSkip(string $url)
{
$handler = [self::class, 'defaultSkipHandler'];
$urls = [];
if (!empty($this->skip)) {
if (isset($this->skip['is']) && is_callable($this->skip['is'])) {
$handler = $this->skip['is'];
}
if (isset($this->skip['urls']) && is_array($this->skip['urls'])) {
$urls = $this->skip['urls'];
}
}
return call_user_func_array($handler, [$url, $urls]);
}
/**
* 默认忽略
*
* @param string $url
* @param array $urls
*
* @return bool
*/
private function defaultSkipHandler(string $url, array $urls)
{
return in_array($url, $urls);
}
/**
* 解析参数
*
* @param string $headerStr
* @param string $payloadStr
*
* @return array
* @throws AccessKeyException
* @throws InvalidTokenException
* @throws SignatureMethodException
*/
private function parseParams(string $headerStr, string $payloadStr)
{
$header = json_decode(base64_decode($headerStr), true);
$payload = json_decode(base64_decode($payloadStr), true);
if (!is_array($header) || !isset($header['alg']) ||
!is_array($payload) || !isset($payload['timestamp']) || !isset($payload['rand_str']) || !isset($payload['access_key']) || !isset($payload['data'])) {
throw new InvalidTokenException('Invalid Sign !');
}
if ($this->timeout > 0 && $this->timeout < (time() - $payload['timestamp'])) {
throw new InvalidTokenException('Sign has expired!');
}
if (!isset($this->roles[$payload['access_key']])) {
throw new AccessKeyException('Access key invalid !');
}
if (!isset($this->signatureMethods[$header['alg']])) {
throw new SignatureMethodException($header['alg'] . ' signatures are not supported !');
}
$alg = $this->signatureMethods[$header['alg']];
if (!class_exists($alg)) {
throw new SignatureMethodException($header['alg'] . ' signatures method configuration error !');
}
$alg = new $alg;
if (!$alg instanceof SignatureInterface) {
throw new SignatureMethodException($header['alg'] . ' signatures method configuration error !');
}
return [$header, $payload, $alg];
}
/**
* 数据效验
*
* @param SignatureInterface $alg
* @param string $encryptStr
* @param string $data
*
* @throws InvalidTokenException
*/
private function dataCheck(SignatureInterface $alg, string $encryptStr, string $data)
{
if (!$alg::dataCheck($encryptStr, $data)) {
throw new InvalidTokenException('invalid Sign !');
}
}
/**
* 签名校验
*
* @param SignatureInterface $alg
* @param string $signatureStr
* @param string $secret
* @param string $signature
*
* @throws InvalidTokenException
*/
private function signatureCheck(SignatureInterface $alg, string $signatureStr, string $secret, string $signature)
{
if (!$alg::signCheck($signatureStr, $secret, $signature)) {
throw new InvalidTokenException('invalid Sign !');
}
}
}