From b8234adee19d46360c3e5941dfaab23c89321c92 Mon Sep 17 00:00:00 2001 From: Tomas Majer Date: Sat, 7 Nov 2026 14:02:34 +0100 Subject: [PATCH] Custom error message for token authorization TokenRepositoryInterface::validToken() may throw InvalidTokenException; its message is returned as the 401 error message. --- CHANGELOG.md | 3 +++ docs/guide/authorization.md | 24 +++++++++++++++++++ docs/sk/guide/authorization.md | 24 +++++++++++++++++++ src/Authorization/TokenAuthorization.php | 8 ++++++- src/Exception/InvalidTokenException.php | 11 +++++++++ src/Misc/TokenRepositoryInterface.php | 8 ++++++- .../BearerTokenAuthorizationTest.php | 21 ++++++++++++++++ 7 files changed, 97 insertions(+), 2 deletions(-) create mode 100644 src/Exception/InvalidTokenException.php diff --git a/CHANGELOG.md b/CHANGELOG.md index faad8bf0e..0329ae48d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) princip Planned for 4.0, developed on `master`. 3.x is maintained on the `3.x` branch. +### Added +* Custom error message for token authorization + ### Changed (BC breaks) * Renamed the unsafe CORS mode `'auto'` (any website can make credentialed requests) to `'reflect-unsafe'` (`CorsMode::ReflectUnsafe`) with the same behaviour plus `Vary: Origin, Referer`: `setCorsHeader('auto')` throws and `api: cors: mode: auto` fails the compilation, both with the allowlist to use instead and the new name (#186). * `ApiPresenter` sends no CORS headers by default (`'off'` instead of `'*'`), with or without the DI extension; set `setCorsAllowedOrigins()` / `cors: allowedOrigins` or `'*'` explicitly. See `UPGRADE-4.0.md` (#186). diff --git a/docs/guide/authorization.md b/docs/guide/authorization.md index 5e859dfd3..14733fea6 100644 --- a/docs/guide/authorization.md +++ b/docs/guide/authorization.md @@ -49,6 +49,30 @@ For a real app, implement `TokenRepositoryInterface` on top of your database. Since 3.6.0, `BasicAuthentication` and `StaticTokenRepository` compare passwords and tokens with `hash_equals()`, in constant time, so the response time does not reveal how much of a token was right. Which values match is the same as before. In your own [token repository](#your-own-authorization) or authorization, compare secrets with `hash_equals()` too. ::: +### Custom error message + +`validToken()` can throw `InvalidTokenException` instead of returning `false`. Its message becomes the `message` in the 401 response, so you can tell the client why the token was refused, for example which permission is missing: + +```php +use Tomaj\NetteApi\Exception\InvalidTokenException; + +public function validToken(string $token): bool +{ + $apiToken = $this->tokens->findActive($token); + if ($apiToken === null) { + return false; // default message: Token doesn't exists or isn't active + } + if (!$apiToken->hasPermission('articles.write')) { + throw new InvalidTokenException('Token is missing permission "articles.write"'); + } + return true; +} +``` + +::: warning +The message is sent to the client as is. Don't put anything sensitive in it. +::: + ## Your own authorization ```php diff --git a/docs/sk/guide/authorization.md b/docs/sk/guide/authorization.md index 710ef07a6..9062535fa 100644 --- a/docs/sk/guide/authorization.md +++ b/docs/sk/guide/authorization.md @@ -49,6 +49,30 @@ V reálnej aplikácii implementujte `TokenRepositoryInterface` nad vašou datab Od verzie 3.6.0 porovnávajú `BasicAuthentication` a `StaticTokenRepository` heslá a tokeny cez `hash_equals()`, v konštantnom čase, takže čas odpovede neprezradí, aká časť tokenu bola správna. Ktoré hodnoty sa zhodujú, je rovnaké ako predtým. Vo vlastnom [repozitári tokenov](#vlastna-autorizacia) alebo autorizácii porovnávajte tajomstvá tiež cez `hash_equals()`. ::: +### Vlastná chybová správa + +`validToken()` môže namiesto `false` hodiť `InvalidTokenException`. Jej správa sa stane `message` v odpovedi 401, takže klientovi viete povedať, prečo token neprešiel, napríklad aké oprávnenie chýba: + +```php +use Tomaj\NetteApi\Exception\InvalidTokenException; + +public function validToken(string $token): bool +{ + $apiToken = $this->tokens->findActive($token); + if ($apiToken === null) { + return false; // predvolená správa: Token doesn't exists or isn't active + } + if (!$apiToken->hasPermission('articles.write')) { + throw new InvalidTokenException('Token is missing permission "articles.write"'); + } + return true; +} +``` + +::: warning +Správa ide klientovi tak, ako je. Nedávajte do nej nič citlivé. +::: + ## Vlastná autorizácia ```php diff --git a/src/Authorization/TokenAuthorization.php b/src/Authorization/TokenAuthorization.php index 79640d35e..bb0ea775a 100644 --- a/src/Authorization/TokenAuthorization.php +++ b/src/Authorization/TokenAuthorization.php @@ -4,6 +4,7 @@ namespace Tomaj\NetteApi\Authorization; +use Tomaj\NetteApi\Exception\InvalidTokenException; use Tomaj\NetteApi\Misc\IpDetectorInterface; use Tomaj\NetteApi\Misc\TokenRepositoryInterface; @@ -44,7 +45,12 @@ public function authorized(): bool return false; } - $result = $this->tokenRepository->validToken($token); + try { + $result = $this->tokenRepository->validToken($token); + } catch (InvalidTokenException $e) { + $this->errorMessage = $e->getMessage(); + return false; + } if (!$result) { $this->errorMessage = 'Token doesn\'t exists or isn\'t active'; return false; diff --git a/src/Exception/InvalidTokenException.php b/src/Exception/InvalidTokenException.php new file mode 100644 index 000000000..f5c5bbd12 --- /dev/null +++ b/src/Exception/InvalidTokenException.php @@ -0,0 +1,11 @@ +assertFalse($bearerTokenAuthorization->authorized()); } + + public function testRepositoryCustomErrorMessage(): void + { + $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer sad0f98uwegoihweg09i4hergy'; + $tokenRepository = new class implements TokenRepositoryInterface { + public function validToken(string $token): bool + { + throw new InvalidTokenException('Missing permission "articles.write"'); + } + + public function ipRestrictions(string $token): ?string + { + return '*'; + } + }; + $bearerTokenAuthorization = new BearerTokenAuthorization($tokenRepository, new StaticIpDetector('34.24.126.44')); + $this->assertFalse($bearerTokenAuthorization->authorized()); + $this->assertSame('Missing permission "articles.write"', $bearerTokenAuthorization->getErrorMessage()); + } }