[英]Get authenticated user with Laravel Passport and grant password
我用 Laravel 做了一個 API REST,現在我正在嘗試使用它。 問題是我需要在 API 中對用戶進行身份驗證,並且我正在使用密碼授予方法。 我可以正確地對用戶進行身份驗證,並且可以獲得訪問令牌,但是從那時起,我在我的消費應用程序中看不到使用訪問令牌檢索經過身份驗證的用戶的方法。
我在 API 中嘗試了這樣的路線:
Route::get('/user', function(Request $request) {
$user = $request->user();
// Even with
$user = Auth::user();
return $user;
});
沒有骰子。 我正在閱讀護照代碼,但我無法弄清楚。 我的猜測是我需要指定一個新的保護類型或其他東西,因為 Laravel Passport 似乎沒有為這種授權類型提供一個......
澄清事情:
或者我可以嗎? 也許我可以擴展驗證密碼授予請求的方法,將生成的訪問令牌與正在驗證的用戶相關聯...... *燈泡亮起*
使用應用程序測試代碼:
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 了解發出請求的用戶。
你忘記了合適的中間件。
Route::get('/user', function(Request $request) {
return Auth::user();
})->middleware('auth:api');
當您不提及auth
中間件時,不會觸發身份驗證流程。 這就是為什么你得到null
。
我和你有同樣的問題。 我在手動定義了身份驗證保護后解決了它。
Route::get('/user', function (Request $request) {
return auth()->guard('api')->user();
});
您需要在每個請求中傳遞回訪問令牌。 請在 此處查看此部分的文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.