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



PHP Snippet 1:

Accept : application/json

PHP Snippet 2:

{
    "message": "Unauthenticated."
}

PHP Snippet 3:

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

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

PHP Snippet 4:

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);
}

PHP Snippet 5:

return abort(401);