简体   繁体   English

Laravel Passport:auth:api表现得像auth:web

[英]Laravel Passport: auth:api behaving like auth:web

I am trying to implement passport in my application to authenticate the api calls. 我正在尝试在我的应用程序中实现passport以验证api调用。 I have done the configuration as mentioned in the official documentation. 我已经完成了官方文档中提到的配置。 I have this in my auth guard: 我在我的认证中有这个:

'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],

And, this in my AuthServiceProvider's boot() method: 而且,这在我的AuthServiceProvider's boot()方法中:

Passport::routes();

And this is the route I am trying to access: 这是我试图访问的route

    Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::group(['namespace' => 'Api', 'middleware' => 'auth:api'], function () {
    // Login Controller
   Route::get('/getclc', 'PreController@getClc');
});

I am sending the header in the request like this: 我在请求中发送header ,如下所示:

Authorization:Bearer $accessToken

My question is: 1. When a protected route is requested, it sends me to login page, but I want it to return the 401. How can I do that? 我的问题是:1。当请求受保护的路由时,它会将我发送到登录页面,但我希望它返回401.我该怎么做?

My laravel version is 5.4.33. 我的laravel版本是5.4.33。

When authentication fails, Laravel throws an AuthenticationException exception. 身份验证失败时,Laravel会抛出AuthenticationException异常。 This exception is handled by your Laravel exception handler, and eventually calls the unauthenticated() method in your app/Exceptions/Handler.php file. 此异常由Laravel异常处理程序处理,并最终在app/Exceptions/Handler.php文件中调用unauthenticated()方法。

You can see from that method that if your request expects a json response, you'll get a 401 Unauthenticated response. 您可以从该方法中看到,如果您的请求需要json响应,您将获得401 Unauthenticated响应。 However, if you're not expecting a json response, it just redirects to the route named "login". 但是,如果您不期望json响应,它只会重定向到名为“login”的路由。 This will obviously fail if you don't have a route named "login". 如果您没有名为“login”的路由,这显然会失败。

Your request "expectsJson" when you send either the "X-Requested-With: XMLHttpRequest" header, or the "Accept: application/json" header. 当您发送“X-Requested-With:XMLHttpRequest”标头或“Accept:application / json”标头时,您的请求“expectedJson”。 Otherwise, it is considered a normal web request. 否则,它被视为普通的Web请求。

If you'd like to change how your application handles unauthenticated users, the unauthenticated() method is the one to change. 如果您想更改应用程序处理未经身份验证的用户的方式,则需要更改unauthenticated()方法。

Add this code on Headers on postman. 在邮递员的标题上添加此代码。

key           Value
Accept        application/json

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM