Laravel 5.6-如何在api控制器中获取auth()-> user()或$ response-> user()? [英] Laravel 5.6 - How to get auth()->user() or $response->user() in api controller?
问题描述
在下面的api.php
路线文件中,有公共路线和私人路线:
In api.php
routes file below, there are public routes and private routes:
Route::group(['namespace' => 'API'], function() {
// Public routes (auth not required)
Route::group([], function() {
Route::get('/testauth1', 'TestController@testauth1');
// more public routes...
});
// Private routes (auth required)
Route::group(['middleware' => 'auth:api'], function() {
Route::get('/testauth2', 'TestController@testauth2');
// more private routes...
});
});
在TestContoller
中,这些是上面调用的2种方法:
In the TestContoller
these are the 2 methods called above:
class TestController extends Controller {
public function testauth1(\Request $request) {
// return auth()->user(); // does not return user
return $request->user(); // does not return user
}
public function testauth2() {
return auth()->user(); // returns user
}
}
由于专用路由组具有auth:api
中间件,因此我们将通过检查Authorization Bearer
标头中提供的令牌来确保对用户进行身份验证.仅当存在有效令牌时,私有路由才会呈现给经过身份验证的用户.这就是TestController@testauth2
正确返回身份验证用户的原因.
Since the private route group has the auth:api
middleware, we will ensure the user is authenticated by checking the token supplied in the Authorization Bearer
header. Only if a valid token is present will the private routes be rendered to the authenticated user. This is why TestController@testauth2
returns the auth user correctly.
现在,任何人都可以使用或不使用令牌访问公共路线.如果Authorization Bearer
标头中没有提供令牌,那么我们将没有经过身份验证的用户,这是有道理的.这就是为什么TestController@testauth1
不返回身份验证用户的原因.但是,当登录的用户访问/testauth1
公共路由时,他们会在Authorization Bearer
标头中提供其令牌,因此,如果不使用auth()->user()
,至少应该使用$request->user()
,则应该在TestController@testauth1
中返回它们,但我们可以似乎无法通过该方法使用其提供的令牌访问用户.
Now, anyone can access the public routes, with or without token. If there is no token supplied in the Authorization Bearer
header, then we'll have no authenticated user, which makes sense. This is why TestController@testauth1
does not return an auth user. However, when a logged in user accesses /testauth1
public route, they provide their token in the Authorization Bearer
header and therefore should be returned in TestController@testauth1
if not with auth()->user()
at least with the $request->user()
but we can't seem to access the user with their supplied token in that method.
您知道我们如何在所有公共路线方法中访问有效令牌用户吗?
Any idea how we can access the valid token user in all public route methods?
推荐答案
将api
防护作为参数传递,以获取授权用户,而无需中间件保护请求.
Pass the api
guard as a parameter to fetch the authorized user without the middleware protecting the request.
$request->user('api');
// Or
auth('api')->user();
这篇关于Laravel 5.6-如何在api控制器中获取auth()-> user()或$ response-> user()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!