1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @copyright Copyright (c) 2016 Canis.io |
4
|
|
|
* @license MIT |
5
|
|
|
*/ |
6
|
|
|
namespace Canis\Lumen\Jwt\Adapters\Lcobucci; |
7
|
|
|
|
8
|
|
|
use Lcobucci\JWT\ValidationData; |
9
|
|
|
use Lcobucci\JWT\Builder; |
10
|
|
|
use Lcobucci\JWT\Signer\Hmac\Sha256; |
11
|
|
|
use Lcobucci\JWT\Parser; |
12
|
|
|
use Lcobucci\JWT\Token; |
13
|
|
|
use Canis\Lumen\Jwt\Contracts\Generator as GeneratorContract; |
14
|
|
|
|
15
|
|
|
class Generator |
16
|
|
|
extends HelperBase |
|
|
|
|
17
|
|
|
implements GeneratorContract |
|
|
|
|
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Generates the token |
21
|
|
|
* @param array $claims |
22
|
|
|
* @return Token |
23
|
|
|
*/ |
24
|
11 |
|
final public function __invoke(array $claims) |
25
|
|
|
{ |
26
|
11 |
|
$signer = new Sha256(); |
27
|
11 |
|
$builder = new Builder(); |
28
|
11 |
|
$claims = array_merge($this->getDefaultClaims(), $claims, $this->getForcedClaims()); |
29
|
11 |
|
if (!$this->checkRequiredClaims(array_keys($claims))) { |
30
|
1 |
|
return false; |
|
|
|
|
31
|
10 |
|
}; |
32
|
10 |
|
foreach ($claims as $claim => $value) { |
33
|
10 |
|
if ($this->isBadClaim($claim)) { |
34
|
1 |
|
continue; |
35
|
|
|
} |
36
|
10 |
|
$builder->set($claim, $value); |
37
|
10 |
|
} |
38
|
10 |
|
$builder->setId(substr(hash('sha256', serialize($claims) . openssl_random_pseudo_bytes(20)), 0, 16), true); |
39
|
10 |
|
$builder->sign($signer, $this->config['secret']); |
40
|
10 |
|
return $builder->getToken(); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Default claims (can be overriden) |
45
|
|
|
* |
46
|
|
|
* @return array |
47
|
|
|
*/ |
48
|
11 |
|
protected function getDefaultClaims() |
49
|
|
|
{ |
50
|
11 |
|
$default = []; |
51
|
11 |
|
if (!empty($this->config['issuer'])) { |
52
|
11 |
|
$default['iss'] = $this->config['issuer']; |
53
|
11 |
|
} |
54
|
11 |
|
if (!empty($this->config['audience'])) { |
55
|
2 |
|
$default['aud'] = $this->config['audience']; |
56
|
2 |
|
} |
57
|
11 |
|
return $default; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Forced claims |
62
|
|
|
* |
63
|
|
|
* @return array |
64
|
|
|
*/ |
65
|
11 |
|
private function getForcedClaims() |
66
|
|
|
{ |
67
|
1 |
|
return [ |
68
|
11 |
|
'iat' => time(), |
69
|
11 |
|
'nbf' => time() + $this->config['nbfOffset'], |
70
|
11 |
|
'exp' => time() + $this->config['expOffset'] |
71
|
11 |
|
]; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Checks if claim is bad |
76
|
|
|
* |
77
|
|
|
* @param string $claim |
78
|
|
|
* @return boolean |
79
|
|
|
*/ |
80
|
10 |
|
private function isBadClaim($claim) |
81
|
|
|
{ |
82
|
10 |
|
return in_array($claim, ['jti']); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|