ApiUtils.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace Shaarli\Api;
  3. use Shaarli\Base64Url;
  4. use Shaarli\Api\Exceptions\ApiAuthorizationException;
  5. /**
  6. * REST API utilities
  7. */
  8. class ApiUtils
  9. {
  10. /**
  11. * Validates a JWT token authenticity.
  12. *
  13. * @param string $token JWT token extracted from the headers.
  14. * @param string $secret API secret set in the settings.
  15. *
  16. * @throws ApiAuthorizationException the token is not valid.
  17. */
  18. public static function validateJwtToken($token, $secret)
  19. {
  20. $parts = explode('.', $token);
  21. if (count($parts) != 3 || strlen($parts[0]) == 0 || strlen($parts[1]) == 0) {
  22. throw new ApiAuthorizationException('Malformed JWT token');
  23. }
  24. $genSign = Base64Url::encode(hash_hmac('sha512', $parts[0] .'.'. $parts[1], $secret, true));
  25. if ($parts[2] != $genSign) {
  26. throw new ApiAuthorizationException('Invalid JWT signature');
  27. }
  28. $header = json_decode(Base64Url::decode($parts[0]));
  29. if ($header === null) {
  30. throw new ApiAuthorizationException('Invalid JWT header');
  31. }
  32. $payload = json_decode(Base64Url::decode($parts[1]));
  33. if ($payload === null) {
  34. throw new ApiAuthorizationException('Invalid JWT payload');
  35. }
  36. if (empty($payload->iat)
  37. || $payload->iat > time()
  38. || time() - $payload->iat > ApiMiddleware::$TOKEN_DURATION
  39. ) {
  40. throw new ApiAuthorizationException('Invalid JWT issued time');
  41. }
  42. }
  43. }