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