使用Laravel和Passport在身份验证失败时响应状态码401? [英] Respond with status code 401 on authentication failure using Laravel and Passport?
问题描述
我正在配置一个Laravel项目以使用Passport令牌身份验证.一切似乎都正常,但是当auth:api
中间件失败时,它以200
状态和响应正文中的一堆HTML响应客户端.相反,我希望它以状态401
进行响应.
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
.
我在Laravel Passport源或文档中找不到有关执行此操作的任何信息.我什至找不到中间件的来源.
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.
我的考试路线:
Route::get('/protected', function () {
return response()->json([
'success' => true
]);
})->middleware('auth:api');
config/auth.php
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
],
],
推荐答案
您可以通过发送带有请求的标头来解决它.
You can solve it by sending this header with your request.
Accept : application/json
这将使用状态代码401
发送此消息.
This will send this message with 401
status code.
{
"message": "Unauthenticated."
}
这篇关于使用Laravel和Passport在身份验证失败时响应状态码401?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!