Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

iftekhs's avatar
Level 13

Return JSON response for unauthenticated user laravel passport.

Hi, I'm using laravel passport. For my protected routes I'm using the "auth:api" middleware and in my app/exceptions/Handler.php I have overwritten the unauthenticated method to return a JSON response if the user is not authenticated. But still it tries to redirect to Login route if the user is not authenticated and trying to access protected route.

Handler.php

class Handler extends ExceptionHandler
{
    /**
     * A list of exception types with their corresponding custom log levels.
     *
     * @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
     */
    protected $levels = [
        //
    ];

    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<\Throwable>>
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */

    protected function unauthenticated($request, AuthenticationException $exception)
    {
        return response()->json(
            [
                'errors' => [
                    'status' => 401,
                    'message' => 'Unthorized',
                ]
            ],
            401
        );
    }

    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }
}

Protected Route

Route::group(['middleware' => 'auth:api'], function () {
    Route::get('/user', [AuthController::class, 'user']);
});

Postman request & response https://drive.google.com/file/d/1lVx7RhuCrSZnLoCTNMfBYUPpNMRm7yT5/view?usp=sharing

0 likes
1 reply
LaryAI's avatar
Level 58

It seems like the issue is with the redirection happening before the JSON response is returned. To prevent this, you can modify the app/Http/Middleware/Authenticate.php file to return a JSON response instead of redirecting.

Here's an example of how you can modify the handle method in Authenticate.php:

public function handle($request, Closure $next, ...$guards)
{
    if ($this->authenticate($request, $guards) === 'authentication_failed') {
        return response()->json([
            'errors' => [
                'status' => 401,
                'message' => 'Unauthenticated',
            ],
        ], 401);
    }

    return $next($request);
}

This will return a JSON response with a 401 status code if the user is not authenticated. Make sure to import the Closure class at the top of the file.

Also, make sure to remove the unauthenticated method from your Handler.php file as it is no longer needed.

With these changes, you should be able to get a JSON response for unauthenticated users.

Please or to participate in this conversation.