vendor/lexik/jwt-authentication-bundle/Encoder/LcobucciJWTEncoder.php line 47

Open in your IDE?
  1. <?php
  2. namespace Lexik\Bundle\JWTAuthenticationBundle\Encoder;
  3. use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTDecodeFailureException;
  4. use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTEncodeFailureException;
  5. use Lexik\Bundle\JWTAuthenticationBundle\Services\JWSProvider\JWSProviderInterface;
  6. /**
  7. * Json Web Token encoder/decoder based on the lcobucci/jwt library.
  8. *
  9. * @author Robin Chalas <robin.chalas@gmail.com>
  10. */
  11. class LcobucciJWTEncoder implements JWTEncoderInterface, HeaderAwareJWTEncoderInterface
  12. {
  13. /**
  14. * @var JWSProviderInterface
  15. */
  16. protected $jwsProvider;
  17. public function __construct(JWSProviderInterface $jwsProvider)
  18. {
  19. $this->jwsProvider = $jwsProvider;
  20. }
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function encode(array $payload, array $header = [])
  25. {
  26. try {
  27. $jws = $this->jwsProvider->create($payload, $header);
  28. } catch (\InvalidArgumentException $e) {
  29. throw new JWTEncodeFailureException(JWTEncodeFailureException::INVALID_CONFIG, 'An error occurred while trying to encode the JWT token. Please verify your configuration (private key/passphrase)', $e, $payload);
  30. }
  31. if (!$jws->isSigned()) {
  32. throw new JWTEncodeFailureException(JWTEncodeFailureException::UNSIGNED_TOKEN, 'Unable to create a signed JWT from the given configuration.', null, $payload);
  33. }
  34. return $jws->getToken();
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function decode($token)
  40. {
  41. try {
  42. $jws = $this->jwsProvider->load($token);
  43. } catch (\Exception $e) {
  44. throw new JWTDecodeFailureException(JWTDecodeFailureException::INVALID_TOKEN, 'Invalid JWT Token', $e);
  45. }
  46. if ($jws->isInvalid()) {
  47. throw new JWTDecodeFailureException(JWTDecodeFailureException::INVALID_TOKEN, 'Invalid JWT Token', null, $jws->getPayload());
  48. }
  49. if ($jws->isExpired()) {
  50. throw new JWTDecodeFailureException(JWTDecodeFailureException::EXPIRED_TOKEN, 'Expired JWT Token', null, $jws->getPayload());
  51. }
  52. if (!$jws->isVerified()) {
  53. throw new JWTDecodeFailureException(JWTDecodeFailureException::UNVERIFIED_TOKEN, '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.', null, $jws->getPayload());
  54. }
  55. return $jws->getPayload();
  56. }
  57. }