forked from lexik/LexikJWTAuthenticationBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDefaultEncoder.php
69 lines (58 loc) · 2.03 KB
/
DefaultEncoder.php
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
<?php
namespace Lexik\Bundle\JWTAuthenticationBundle\Encoder;
use InvalidArgumentException;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTDecodeFailureException;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTEncodeFailureException;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWSProviderInterface;
/**
* Default Json Web Token encoder/decoder.
*
* @author Robin Chalas <[email protected]>
*/
class DefaultEncoder implements JWTEncoderInterface
{
/**
* @var JWSProviderInterface
*/
protected $jwsProvider;
/**
* @param JWSProviderInterface $jwsProvider
*/
public function __construct(JWSProviderInterface $jwsProvider)
{
$this->jwsProvider = $jwsProvider;
}
/**
* {@inheritdoc}
*/
public function encode(array $payload)
{
try {
$jws = $this->jwsProvider->create($payload);
} catch (InvalidArgumentException $e) {
throw new JWTEncodeFailureException('An error occurred while trying to encode the JWT token.', $e);
}
if (!$jws->isSigned()) {
throw new JWTEncodeFailureException('Unable to create a signed JWT from the given configuration.');
}
return $jws->getToken();
}
/**
* {@inheritdoc}
*/
public function decode($token)
{
try {
$jws = $this->jwsProvider->load($token);
} catch (InvalidArgumentException $e) {
throw new JWTDecodeFailureException('Invalid JWT Token', $e);
}
if ($jws->isExpired()) {
throw new JWTDecodeFailureException('Expired JWT token');
}
if (!$jws->isVerified()) {
throw new JWTDecodeFailureException('Unable to verify the given JWT through the given configuration. If the "lexik_jwt_authentication.encoder" encryption options have been changed since your last authentication, please renew the token. If the problem persists, verify that the configured keys/passphrase are valid.');
}
return $jws->getPayload();
}
}