1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the BEAR.JwtAuthModule package. |
5
|
|
|
* |
6
|
|
|
* @license http://opensource.org/licenses/MIT MIT |
7
|
|
|
*/ |
8
|
|
|
namespace BEAR\JwtAuth\Encoder; |
9
|
|
|
|
10
|
|
|
use BEAR\JwtAuth\Annotation\Algo; |
11
|
|
|
use BEAR\JwtAuth\Annotation\PassPhrase; |
12
|
|
|
use BEAR\JwtAuth\Annotation\PrivateKey; |
13
|
|
|
use BEAR\JwtAuth\Annotation\PublicKey; |
14
|
|
|
use BEAR\JwtAuth\Exception\InvalidTokenException; |
15
|
|
|
use BEAR\JwtAuth\Exception\JwtException; |
16
|
|
|
use Namshi\JOSE\JWS; |
17
|
|
|
|
18
|
|
|
class NamshiAsymmetric implements JwtEncoderInterface |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var JWS |
22
|
|
|
*/ |
23
|
|
|
private $jws; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var string |
27
|
|
|
*/ |
28
|
|
|
private $algo; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var string |
32
|
|
|
*/ |
33
|
|
|
private $privateKey; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @var string |
37
|
|
|
*/ |
38
|
|
|
private $publicKey; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @var string |
42
|
|
|
*/ |
43
|
|
|
private $passPhrase; |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @Algo("algo") |
47
|
|
|
* @PrivateKey("privateKey") |
48
|
|
|
* @PublicKey("publicKey") |
49
|
|
|
* @PassPhrase("passPhrase") |
50
|
|
|
*/ |
51
|
4 |
|
public function __construct(string $algo, string $privateKey, string $publicKey, string $passPhrase) |
52
|
|
|
{ |
53
|
4 |
|
$this->jws = new JWS(['typ' => 'JWT', 'alg' => $algo]); |
54
|
4 |
|
$this->algo = $algo; |
55
|
4 |
|
$this->privateKey = $privateKey; |
56
|
4 |
|
$this->publicKey = $publicKey; |
57
|
4 |
|
$this->passPhrase = $passPhrase; |
58
|
4 |
|
} |
59
|
|
|
|
60
|
1 |
|
public function encode(array $payload) : string |
61
|
|
|
{ |
62
|
|
|
try { |
63
|
1 |
|
$this->jws->setPayload($payload)->sign($this->privateKey, $this->passPhrase); |
|
|
|
|
64
|
|
|
|
65
|
1 |
|
return (string) $this->jws->getTokenString(); |
66
|
|
|
} catch (Exception $e) { |
|
|
|
|
67
|
|
|
throw new JwtException($e->getMessage()); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
2 |
|
public function decode(string $token) : array |
72
|
|
|
{ |
73
|
|
|
try { |
74
|
2 |
|
$jws = $this->jws->load($token, false); |
75
|
1 |
|
} catch (\InvalidArgumentException $e) { |
76
|
1 |
|
throw new InvalidTokenException($e->getMessage()); |
77
|
|
|
} |
78
|
|
|
|
79
|
1 |
|
if (!$jws->verify($this->publicKey, $this->algo)) { |
80
|
|
|
throw new InvalidTokenException('Invalid Token'); |
81
|
|
|
} |
82
|
|
|
|
83
|
1 |
|
return (array) $jws->getPayload(); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|
It seems like the type of the argument is not accepted by the function/method which you are calling.
In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.
We suggest to add an explicit type cast like in the following example: