laravel Passport:在auth:api中间件外部以及在返回的用户对象内部,请求user()返回null [英] laravel passport: Request user() returning null outside auth:api middleware, and inside returning user object

查看:182
本文介绍了laravel Passport:在auth:api中间件外部以及在返回的用户对象内部,请求user()返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用auth:api中间件获取登录的用户详细信息时,它将在我的控制器函数中返回包含详细信息的用户对象.

When I am tring to get loggedin user details using auth:api middleware, it returns user object with details in my controller function.

api.php (with auth:api middleware returns User object)

Route::group(['middleware' => 'auth:api'], function() {
    Route::get('users/mentor_details/{uuid}','UserController@getMentorProfileDetails');
});

但是,当我尝试在auth:api中间件之外获取登录的用户详细信息时,它将返回null.

But when I am trying to get loggedin user details outside this auth:api middleware, it returns null.

api.php (without auth:api middleware return null)

Route::get('users/mentor_details/{uuid}','UserController@getMentorProfileDetails');

推荐答案

如果未提供auth中间件,或者未提供auth中间件而提供了中间件,则使用默认的guard来确定用户.除非您在config/auth.php文件中进行了更改,否则默认防护为web防护.

When the auth middleware is not provided, or is provided without specifying the guard, the default guard is used to determine the user. Unless you have changed this in your config/auth.php file, the default guard is the web guard.

因此,当您转到不受特定身份验证中间件保护的路由时,加载的用户就是web防护提供的用户.

So, when you go to a route that is not protected by a specific auth middleware, the user that is loaded is the one provided by the web guard.

因此,即使您可能要发送使用令牌来使用特定用户,web保护也对此一无所知,并且由于您没有用户通过web保护登录,因此您可以获得null用户.

Therefore, even though you may be sending the bearer token to use a specific user, the web guard doesn't know anything about that, and since you have no user logged in via the web guard, you are getting a null user.

您有四个选择:

  1. 确保路由受auth:api中间件保护,该中间件指定了api防护.但是,这将不允许访客访问该URL.

  1. Make sure the route is protected by the auth:api middleware, which specifies the api guard. This, however, will not allow guests to access the url.

config/auth.php文件中将默认防护更改为api.这可能不是您想要的,特别是如果您有普通的Web用户.

Change your default guard to api in your config/auth.php file. This is probably not what you want to do, especially if you do have normal web users.

api防护中告诉您想要用户的请求. $request->user()方法将防护作为参数,因此,如果执行$request->user('api'),它将使用api防护来检索用户.

Tell the request you want the user from the api guard. The $request->user() method takes a guard as an argument, so if you do $request->user('api'), it will retrieve the user using the api guard.

直接从api保护对象中获取用户:auth()->guard('api')->user().

Get the user from the api guard directly: auth()->guard('api')->user().

这篇关于laravel Passport:在auth:api中间件外部以及在返回的用户对象内部,请求user()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆