Laravel API 身份验证重定向到登录而不是简单的 401 页面

Sty*_*h1t 3 php laravel laravel-5.5

我正在使用 Laravel 5.5.34,这是我第一次创建 API。

api_token在用户表中添加了一列并在注册时生成令牌。

后来,我打开routes/api.php文件并添加了以下代码:

Route::middleware( 'auth:api' )->get( 'test', function( Request $request ){
    dd( \Auth::user() );
});
Run Code Online (Sandbox Code Playgroud)

当我api_token在 POST 数据中发送一个时,此代码工作正常,但如果我不发送,它会重定向到登录页面而不是 401 页面,即使我发送了一个Accept: application/json标题。

如何使它重定向到 401 页面?

Ant*_*hev 5

设置标题“接受:应用程序/json”必须足够。

Laravel 5.5 在 App\Exceptions\Handler.php “未经身份验证”方法中处理«AuthenticationException»。它的样子:

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

    return redirect()->guest(route('login'));
}
Run Code Online (Sandbox Code Playgroud)

在“expectsJson”方法https://laravel.com/api/5.3/Illuminate/Http/Request.html#method_expectsJson 中,执行检查请求头“Accept”包含“json”模式:

return isset($acceptable[0]) && Str::contains($acceptable[0], ['/json', '+json']);
Run Code Online (Sandbox Code Playgroud)

因此,您必须检查您的请求是否在$request?expectsJson()调用中实际返回true。在请求中设置 Accept 标头时可能会出错。