Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
24 changes: 24 additions & 0 deletions docs/guide/authorization.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 24 additions & 0 deletions docs/sk/guide/authorization.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 7 additions & 1 deletion src/Authorization/TokenAuthorization.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Tomaj\NetteApi\Authorization;

use Tomaj\NetteApi\Exception\InvalidTokenException;
use Tomaj\NetteApi\Misc\IpDetectorInterface;
use Tomaj\NetteApi\Misc\TokenRepositoryInterface;

Expand Down Expand Up @@ -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;
Expand Down
11 changes: 11 additions & 0 deletions src/Exception/InvalidTokenException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace Tomaj\NetteApi\Exception;

use Exception;

final class InvalidTokenException extends Exception
{
}
8 changes: 7 additions & 1 deletion src/Misc/TokenRepositoryInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,16 @@

namespace Tomaj\NetteApi\Misc;

use Tomaj\NetteApi\Exception\InvalidTokenException;

interface TokenRepositoryInterface
{
/**
* Return true if token is valid, otherwise return false
* Return true if token is valid, otherwise return false or throw InvalidTokenException with custom error message
*
* @param string $token
* @return bool
* @throws InvalidTokenException
*/
public function validToken(string $token): bool;

Expand Down
21 changes: 21 additions & 0 deletions tests/Authorization/BearerTokenAuthorizationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

use PHPUnit\Framework\TestCase;
use Tomaj\NetteApi\Authorization\BearerTokenAuthorization;
use Tomaj\NetteApi\Exception\InvalidTokenException;
use Tomaj\NetteApi\Misc\StaticTokenRepository;
use Tomaj\NetteApi\Misc\TokenRepositoryInterface;
use Tomaj\NetteApi\Misc\StaticIpDetector;

final class BearerTokenAuthorizationTest extends TestCase
Expand Down Expand Up @@ -115,4 +117,23 @@ public function testTokenWithDisabledAccess(): void
$bearerTokenAuthorization = new BearerTokenAuthorization($bearerTokenRepository, $ipDetector);
$this->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());
}
}
Loading