1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the Guarded Authentication package. |
4
|
|
|
* |
5
|
|
|
* (c) Jafar Jabr <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Jafar\Bundle\GuardedAuthenticationBundle\Api\JWSProvider; |
12
|
|
|
|
13
|
|
|
use Jafar\Bundle\GuardedAuthenticationBundle\Api\JWSCreator\JWSCreator; |
14
|
|
|
use Jafar\Bundle\GuardedAuthenticationBundle\Api\JWTSigner\JWS; |
15
|
|
|
use Jafar\Bundle\GuardedAuthenticationBundle\Api\KeyLoader\KeyLoaderInterface; |
16
|
|
|
use Jafar\Bundle\GuardedAuthenticationBundle\Api\KeyLoader\LoadedJWS; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Class JWSProvider. |
20
|
|
|
* |
21
|
|
|
* @author Jafar Jabr <[email protected]> |
22
|
|
|
*/ |
23
|
|
|
class JWSProvider implements JWSProviderInterface |
24
|
|
|
{ |
25
|
|
|
const SIGNATUREALGORITHM = 'RS256'; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var KeyLoaderInterface |
29
|
|
|
*/ |
30
|
|
|
private $keyLoader; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @var int |
34
|
|
|
*/ |
35
|
|
|
private $ttl; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @var int |
39
|
|
|
*/ |
40
|
|
|
private $refresh_ttl; |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param KeyLoaderInterface $keyLoader |
44
|
|
|
* @param int $ttl |
45
|
|
|
* @param int $refresh_ttl |
46
|
|
|
* |
47
|
|
|
* @throws \InvalidArgumentException If the given ttl is not numeric |
48
|
|
|
*/ |
49
|
|
|
public function __construct(KeyLoaderInterface $keyLoader, $ttl, $refresh_ttl) |
50
|
|
|
{ |
51
|
|
|
$this->keyLoader = $keyLoader; |
52
|
|
|
$this->ttl = $ttl; |
53
|
|
|
$this->refresh_ttl = $refresh_ttl; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* {@inheritdoc} |
58
|
|
|
*/ |
59
|
|
|
public function create(array $payload, string $type = 'Main') |
60
|
|
|
{ |
61
|
|
|
$jws = new JWS(['alg' => self::SIGNATUREALGORITHM]); |
62
|
|
|
$claims = ['iat' => time()]; |
63
|
|
|
if ('Main' == $type) { |
64
|
|
|
$claims['exp'] = time() + $this->ttl; |
65
|
|
|
} else { |
66
|
|
|
$claims['exp'] = time() + $this->refresh_ttl; |
67
|
|
|
} |
68
|
|
|
$jws->setPayload($payload + $claims); |
69
|
|
|
$jws->sign( |
70
|
|
|
$this->keyLoader->loadKey('private') |
71
|
|
|
); |
72
|
|
|
|
73
|
|
|
return new JWSCreator($jws->getTokenString(), $jws->isSigned()); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* {@inheritdoc} |
78
|
|
|
*/ |
79
|
|
|
public function load($token) |
80
|
|
|
{ |
81
|
|
|
$jws = JWS::load($token, false, null); |
82
|
|
|
|
83
|
|
|
return new LoadedJWS( |
84
|
|
|
$jws->getPayload(), |
85
|
|
|
$jws->verify($this->keyLoader->loadKey('public'), self::SIGNATUREALGORITHM), |
86
|
|
|
null !== $this->ttl |
87
|
|
|
); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|