'Respond with status code 401 on authentication failure using Laravel and Passport?

I'm configuring a Laravel project to use Passport token authentication. Everything seems to be working, but when the auth:api middleware fails, it responds to the client with a status of 200 and a bunch of HTML in the response body. Instead, I want it to respond with a status of 401.

I can't find anything in the Laravel Passport source or documentation about doing something like this. I can't even find the source for the middleware.

My test route:

Route::get('/protected', function () {
    return response()->json([
        'success' => true
    ]);
})->middleware('auth:api');

config/auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'appUsers',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],

    'appUsers' => [
        'driver' => 'eloquent',
        'model' => App\Models\AppUser::class
    ],
],


Solution 1:[1]

You can solve it by sending this header with your request.

Accept : application/json

This will send this message with 401 status code.

{
    "message": "Unauthenticated."
}

Solution 2:[2]

TLDR

You need to make sure the requests include the Accept: application/json header.

Details

If a user does not authenticate, Laravel will throw an AuthenticationException.

This exception is handled by the render method in Illuminate/Foundation/Exceptions/Handler.php, and will in turn call the the unauthenticated() method which is defined in your app/Exceptions/Handler.php:

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('login'));
}

As you can see, by default, if the request expects a JSON response, you'll get a 401 with a JSON error body. If the request does not expect JSON, the request is redirected to the login page.

The expectsJson() method will return true if your request has either the Accept: application/json header, or the X-Requested-With: XMLHttpRequest. The Accept: application/json header is more appropriate for api calls, whereas the X-Requested-With: XMLHttpRequest header is used for ajax calls.

So, without changing any of your application code, just make sure the requests include the Accept: application/json header.

However, if you need to have a different action happen when a user is not authenticated, you can modify this unauthenticated() method in app/Exceptions/Handler.php:

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    // return a plain 401 response even when not a json call
    return response('Unauthenticated.', 401);
}

Solution 3:[3]

In middleware you can return like this:

return abort(401);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ariful Haque
Solution 2
Solution 3 Serdar Sayg?l?