Laravel 5.6 - 如何在 api 控制器中获取 auth()->user() 或 $response->user()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50709659/
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-09-14 17:47:40  来源:igfitidea点击:

Laravel 5.6 - How to get auth()->user() or $response->user() in api controller?

laravellaravel-5laravel-5.5laravel-5.6laravel-passport

提问by Wonka

In api.phproutes file below, there are public routes and private routes:

api.php下面的路由文件中,有公共路由和私有路由:

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...
     });

});

In the TestContollerthese are the 2 methods called above:

TestContoller这些是上面调用的两种方法:

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
    }

}

Since the private route group has the auth:apimiddleware, we will ensure the user is authenticated by checking the token supplied in the Authorization Bearerheader. Only if a valid token is present will the private routes be rendered to the authenticated user. This is why TestController@testauth2returns the auth user correctly.

由于私有路由组具有auth:api中间件,我们将通过检查Authorization Bearer标头中提供的令牌来确保用户通过身份验证。仅当存在有效令牌时,私有路由才会呈现给经过身份验证的用户。这就是TestController@testauth2正确返回 auth 用户的原因。

Now, anyone can access the public routes, with or without token. If there is no token supplied in the Authorization Bearerheader, then we'll have no authenticated user, which makes sense. This is why TestController@testauth1does not return an auth user. However, when a logged in user accesses /testauth1public route, they provide their token in the Authorization Bearerheader and therefore should be returned in TestController@testauth1if 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.

现在,任何人都可以使用或不使用令牌访问公共路由。如果Authorization Bearer标头中没有提供令牌,那么我们将没有经过身份验证的用户,这是有道理的。这就是为什么TestController@testauth1不返回 auth 用户的原因。但是,当登录的用户访问/testauth1公共路由时,他们在Authorization Bearer标头中提供了他们的令牌,因此TestController@testauth1如果没有auth()->user(),至少应该返回,$request->user()但我们似乎无法在该方法中使用他们提供的令牌访问用户。

Any idea how we can access the valid token user in all public route methods?

知道我们如何在所有公共路由方法中访问有效的令牌用户吗?

回答by Aken Roberts

Pass the apiguard as a parameter to fetch the authorized user without the middleware protecting the request.

api守卫作为参数传递以获取授权用户,而无需中间件保护请求。

$request->user('api');

// Or

auth('api')->user();

回答by Mark Walet

You are referencing Requestfrom a root namespace: \Request. Instead, you should reference the Illuminate\Http\Requestclass.

您正在Request从根命名空间进行引用:\Request. 相反,您应该引用Illuminate\Http\Request该类。

You should remove the \from your parameter and add the following line to your imports.

您应该\从您的参数中删除并将以下行添加到您的导入中。

use Illuminate\Http\Request;

use Illuminate\Http\Request;

Alternatively, you could also reference the request class directly in your method:

或者,您也可以直接在您的方法中引用请求类:

class TestController extends Controller {

    public function testauth1(Illuminate\Http\Request $request) {
        return $request->user();
    }

    public function testauth2() {
        return auth()->user(); // returns user
    }

}

The auth()helper method or AuthFacade is globally available. It doesn't depend on the request that you are trying to access. The same goes for the request()and Request::helpers I believe. In the case you are giving, you are referencing a wrong Request instance, hence giving a unexpected result.

auth()辅助方法或Auth门面是全球可用。它不取决于您尝试访问的请求。我相信的帮助者request()Request::帮助者也是如此。在你给出的情况下,你引用了一个错误的 Request 实例,因此给出了一个意想不到的结果。