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
    ],
],

推荐答案

您可以通过将此标题与请求一起发送来解决此问题.

Accept : application/json

这将发送带有401个状态代码的消息.

{
    "message": "Unauthenticated."
}

Laravel相关问答推荐

Laravel将变量从模板到已发布的供应商模板

无法找到用户sail:passwd 文件中没有匹配的条目

Laravel - 如果值包含某个字符串(取自搜索输入),则查询模型

Laravel 6 Passport 在错误的凭证上返回 400 Bad request

如何通过一个 laravel 安装处理子域

Laravel 5.1 是否与 PHP 7 兼容

Laravel Input:all() 忽略禁用的输入

从 sqlite DB 登录 Laravel,得到PDOException 找不到驱动程序

在 Laravel 中将 Public 添加到assets资源路径

如何在没有 Artisan 的情况下运行 Laravel?

如何在 Laravel 5.1 中为Electron邮件添加标题

Laravel 分页方法不适用于 map 集合?

如何使用命令行手动运行 laravel/lumen 作业(job)

Laravel hasManyThrough

Laravel X-CSRF-Token 与 POSTMAN 不匹配

Laravel 4 - 一个表单中有两个提交按钮,并且两个提交都由不同的操作处理

如何判断是否连接到 Laravel 4 中的数据库?

Laravel 如何在 Eloquent 模型中添加自定义函数?

如何从 laravel 5.1 中数据库表的 created_at 属性中 Select 年份和月份?

Laravel Eager加载与显式连接