Hi everyone,
I’m working on a Laravel 11 application with two authentication guards:
- web for session-based authentication.
- jwt for API token-based authentication using JWT.
The issue I’m facing is that when I use the auth:jwt middleware and the user isn’t authenticated, instead of returning a JSON response, the application redirects to the login page. This behavior is fine for web routes but not for API endpoints.
In previous versions of Laravel, I would override the unauthenticated method in app/Exceptions/Handler.php to handle this. However, in Laravel 11, the app/Exceptions/Handler.php file is no longer used, and configuration is done in bootstrap/app.php.
Here’s my current setup :
Guards in config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'jwt' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
bootstrap/app.php
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use App\Http\Middleware\RoleMiddleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->validateCsrfTokens(except: [
'http://127.0.0.1:8000/api/*',
]);
$middleware->alias([
'role' => RoleMiddleware::class,
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
Problem
When an unauthenticated request hits an API route protected by auth:jwt, it redirects to the login page instead of returning a JSON response like:
{
"error": "Unauthenticated",
"message": "Token is invalid or missing."
}
What I’ve Tried
I know that in Laravel 11, exception handling is configured in bootstrap/app.php using the withExceptions callback. I need to customize the behavior for unauthenticated requests based on the guard being used.
Question
How can I modify the bootstrap/app.php file to ensure that:
- Requests using the jwt guard return a JSON response when unauthenticated.
- Requests using the web guard continue to redirect to the login page.
Thanks in advance for your help!