diff --git a/src/API/Middleware/HandleAuthentication.php b/src/API/Middleware/HandleAuthentication.php index c40b890a4ce..65c0a1faa63 100644 --- a/src/API/Middleware/HandleAuthentication.php +++ b/src/API/Middleware/HandleAuthentication.php @@ -3,6 +3,7 @@ namespace Statamic\API\Middleware; use Closure; +use Statamic\Exceptions\ApiAuthenticationException; class HandleAuthentication { @@ -18,7 +19,7 @@ public function handle($request, Closure $next) ($token = config('statamic.api.auth_token')) && ($request->bearerToken() !== $token) ) { - abort(401); + throw new ApiAuthenticationException; } return $next($request); diff --git a/src/Exceptions/ApiAuthenticationException.php b/src/Exceptions/ApiAuthenticationException.php new file mode 100644 index 00000000000..2987ad8d97f --- /dev/null +++ b/src/Exceptions/ApiAuthenticationException.php @@ -0,0 +1,18 @@ +json( + ['message' => $this->getMessage()], + 401, + ['WWW-Authenticate' => 'Bearer'], + ); + } +} diff --git a/tests/API/AuthenticationTest.php b/tests/API/AuthenticationTest.php index 26914ab1998..72f1ea5332d 100644 --- a/tests/API/AuthenticationTest.php +++ b/tests/API/AuthenticationTest.php @@ -40,28 +40,50 @@ public function it_cant_authenticate_with_invalid_auth_token() Facades\Config::set('statamic.api.auth_token', 'foobar'); $this - ->withToken($token = 'invalid') - ->getJson($url = '/api/collections/articles/entries') - ->assertUnauthorized(); + ->withToken('invalid') + ->getJson('/api/collections/articles/entries') + ->assertUnauthorized() + ->assertHeader('WWW-Authenticate', 'Bearer') + ->assertExactJson(['message' => 'Unauthenticated.']); + } + + #[Test] + public function it_cant_authenticate_without_auth_token() + { + Facades\Config::set('statamic.api.auth_token', 'foobar'); $this - ->withToken($token) - ->get($url) - ->assertUnauthorized(); + ->getJson('/api/collections/articles/entries') + ->assertUnauthorized() + ->assertHeader('WWW-Authenticate', 'Bearer') + ->assertExactJson(['message' => 'Unauthenticated.']); } #[Test] - public function it_cant_authenticate_without_auth_token() + public function it_returns_the_same_json_response_when_debug_mode_is_enabled() { + Facades\Config::set('app.debug', true); Facades\Config::set('statamic.api.auth_token', 'foobar'); $this - ->getJson($url = '/api/collections/articles/entries') - ->assertUnauthorized(); + ->getJson('/api/collections/articles/entries') + ->assertUnauthorized() + ->assertHeader('WWW-Authenticate', 'Bearer') + ->assertExactJson(['message' => 'Unauthenticated.']); + } + + #[Test] + public function it_returns_json_for_unauthenticated_requests() + { + Facades\Config::set('statamic.api.auth_token', 'foobar'); $this - ->get($url) - ->assertUnauthorized(); + ->withHeader('Accept', 'text/html') + ->get('/api/collections/articles/entries') + ->assertUnauthorized() + ->assertHeader('Content-Type', 'application/json') + ->assertHeader('WWW-Authenticate', 'Bearer') + ->assertExactJson(['message' => 'Unauthenticated.']); } #[Test]