5 use Shaarli\Api\Exceptions\ApiAuthorizationException
;
10 * Utility functions for the API.
15 * Validates a JWT token authenticity.
17 * @param string $token JWT token extracted from the headers.
18 * @param string $secret API secret set in the settings.
20 * @throws ApiAuthorizationException the token is not valid.
22 public static function validateJwtToken($token, $secret)
24 $parts = explode('.', $token);
25 if (count($parts) != 3 || strlen($parts[0]) == 0 || strlen($parts[1]) == 0) {
26 throw new ApiAuthorizationException('Malformed JWT token');
29 $genSign = hash_hmac('sha512', $parts[0] .'.'. $parts[1], $secret);
30 if ($parts[2] != $genSign) {
31 throw new ApiAuthorizationException('Invalid JWT signature');
34 $header = json_decode(base64_decode($parts[0]));
35 if ($header === null) {
36 throw new ApiAuthorizationException('Invalid JWT header');
39 $payload = json_decode(base64_decode($parts[1]));
40 if ($payload === null) {
41 throw new ApiAuthorizationException('Invalid JWT payload');
44 if (empty($payload->iat
)
45 || $payload->iat
> time()
46 || time() - $payload->iat
> ApiMiddleware
::$TOKEN_DURATION
48 throw new ApiAuthorizationException('Invalid JWT issued time');