Jwt.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Utils;
  3. use App\Utils\Config;
  4. use Firebase\JWT\JWT as FirebaseJwt;
  5. use Firebase\JWT\Key as FirebaseKey;
  6. use Exception;
  7. class Jwt
  8. {
  9. private const configFilename = 'jwt';
  10. private const algorithm = 'RS256';
  11. private $privateKey;
  12. private $publicKey;
  13. public function __construct()
  14. {
  15. $this->mount();
  16. }
  17. private function mount()
  18. {
  19. $config = Config::getFromFilename(self::configFilename);
  20. $this->privateKey = file_get_contents($config['privateKeyPath']);
  21. $this->publicKey = file_get_contents($config['publicKeyPath']);
  22. if ($this->privateKey === false) {
  23. throw new Exception(sprinft('JWT private key file "%s" cannot be found.', $config['privateKeyPath']));
  24. }
  25. if ($this->publicKey === false) {
  26. throw new Exception(sprintf('JWT public key file "%s" cannot be found.', $config['publicKeyPath']));
  27. }
  28. }
  29. /*
  30. * Genera un token JWT.
  31. */
  32. public function encode(array $payload)
  33. {
  34. return FirebaseJwt::encode($payload, $this->privateKey, self::algorithm);
  35. }
  36. /*
  37. * Decodifica un token JWT.
  38. */
  39. public function decode(string $jwt)
  40. {
  41. return FirebaseJwt::decode($jwt, new FirebaseKey($this->publicKey, self::algorithm));
  42. }
  43. }