php 使用 Laravel 和 Passport 在身份验证失败时响应状态代码 401?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42657180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:40:30  来源:igfitidea点击:

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

phplaravelauthentication

提问by SimpleJ

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

我正在配置 Laravel 项目以使用 Passport 令牌身份验证。一切似乎都在工作,但是当auth:api中间件出现故障时,它会以状态200和响应正文中的一堆 HTML 响应客户端。相反,我希望它以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.

我在 Laravel Passport 源或文档中找不到任何关于执行此类操作的内容。我什至找不到中间件的来源。

My test route:

我的测试路线:

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

config/auth.php

配置/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
    ],
],

回答by Ariful Haque

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

您可以通过随请求发送此标头来解决此问题。

Accept : application/json

This will send this message with 401status code.

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

{
    "message": "Unauthenticated."
}

回答by patricus

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

如果用户没有进行身份验证,Laravel 将抛出一个AuthenticationException.

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

此异常由 中的render方法处理Illuminate/Foundation/Exceptions/Handler.php,并将依次调用unauthenticated()在您的 中定义的方法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.

如您所见,默认情况下,如果请求需要 JSON 响应,您将收到带有 JSON 错误正文的 401。如果请求不需要 JSON,则请求将重定向到登录页面。

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

expectsJson(),如果您的要求有两种方法将返回trueAccept: application/json头,或X-Requested-With: XMLHttpRequest。所述Accept: application/json报头是更适合于API调用,而X-Requested-With: XMLHttpRequest报头用于AJAX调用。

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

因此,无需更改任何应用程序代码,只需确保请求包含Accept: application/json标头即可。

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:

但是,如果您需要在用户未通过身份验证时发生不同的操作,您可以unauthenticated()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);
}

回答by Serdar Sayg?l?

In middleware you can return like this:

在中间件中,您可以像这样返回:

return abort(401);