我用Laravel做了一个API REST,现在我正在尝试使用它 . 问题是我需要在API中验证用户,我正在使用Password Grant方法 . 我可以正确地验证用户,我可以获得访问令牌,但从那时起,我没有看到在我的消费应用程序中使用访问令牌检索经过身份验证的用户的方法 .
我尝试使用这样的路由API:
Route::get('/user', function(Request $request) {
$user = $request->user();
// Even with
$user = Auth::user();
return $user;
});
没有骰子 . 我正在阅读Passport代码,但我无法弄明白 . 我的猜测是我需要指定一个新的防护类型或类似东西,因为Laravel Passport似乎没有提供这种类型的防护类型......
澄清事情:
-
我有一个API REST应用程序,它是oAuth2服务器 .
-
我有另一个使用API REST的应用程序 .
-
我确实知道工作流程 . 在我的情况下,使用密码授予,我在我的消费者应用程序中获取用户凭据,然后我向/ oauth / token发出请求,指定grant_type为 password ,我提供用户凭据以及我的客户凭据,我相信他们用“ php artisan passport:client --password ”生成(注意--password选项)
-
我可以毫无问题地获得访问令牌 . 我现在需要的是获取我刚刚从API REST验证的用户的JSON表示 . 但问题是:我只有一个访问令牌 . 我无法与用户联系 .
或者我可以吗?也许我可以扩展验证密码授予请求的方法,以将生成的访问令牌与正在验证的用户相关联...... * light bulb turns on*
Consuming application test code:
try {
$client = new Client();
$result = $client->post('https://myapi.com/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => '5',
'client_secret' => 'my_secret',
'username' => 'user_I_am_authenticating',
'password' => 'the_user_password',
'scope' => '',
]
]);
$access_token = json_decode((string) $result->getBody(), true)['access_token'];
$result = $client->get('https://myapi.com/client/user', [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => "Bearer $access_token",
]
]);
return (string) $result->getBody();
} catch (GuzzleException $e) {
return "Exception!: " . $e->getMessage();
}
请注意, https://myapi.com/client/user 路由只是我在API中进行测试的路径 . 该路线定义为:
Route::get('/user', function(Request $request) {
return $request->user();
});
现在 . 我知道这不起作用 . 这就是我想要实现的目标 . 知道在给定access_token / bearer_token的情况下发出请求的用户 .
谢谢 .
3 回答
你忘记了适当的中间件 .
如果不提及
auth
中间件,则不会触发身份验证流程 . 这就是你得到null
的原因 .我和你有同样的问题 . 我手动定义了auth后卫后解决了它 .
您需要在每次请求时都返回Access令牌 . 请查看此部分的文档here