fix(auth): return JSON 401 for unauthenticated requests unconditionally

The previous Authenticate::redirectTo() -> null fix was incomplete:
Laravel's default Handler::unauthenticated() still falls back to
route('login') via '$exception->redirectTo() ?? route('login')'
whenever the request isn't detected as expectsJson() (no Accept:
application/json or X-Requested-With header), which throws
RouteNotFoundException since this app has no named login route.

Override unauthenticated() directly so this pure-API backend always
returns a JSON 401, regardless of request headers.
This commit is contained in:
Tim Stollberg 2026-07-18 16:09:04 +07:00
parent 0638d9c143
commit abbd92ef85

View file

@ -2,7 +2,9 @@
namespace App\Exceptions; namespace App\Exceptions;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Throwable; use Throwable;
class Handler extends ExceptionHandler class Handler extends ExceptionHandler
@ -27,4 +29,14 @@ public function register(): void
// //
}); });
} }
/**
* This app is a pure JSON API (SPA frontend, no server-rendered login route),
* so unauthenticated requests always get a 401 JSON response instead of
* Laravel's default redirect-to-login fallback.
*/
protected function unauthenticated($request, AuthenticationException $exception): JsonResponse
{
return response()->json(['message' => $exception->getMessage()], 401);
}
} }