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.
您有四个选择:
-
确保路由受
auth:api
中间件保护,该中间件指定了api
防护.但是,这将不允许访客访问该URL.
Make sure the route is protected by the
auth:api
middleware, which specifies theapi
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()
.