簡體   English   中英

使用 Laravel Passport 獲取經過身份驗證的用戶並授予密碼

[英]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 似乎沒有為這種授權類型提供一個......

澄清事情:

  • 我有一個 API REST 應用程序,它是 oAuth2 服務器。
  • 我有另一個使用 API REST 的應用程序。
  • 我知道工作流程。 在我的情況下,使用 Password Grant,我在我的消費者應用程序中獲取用戶憑據,然后我向 /oauth/token 發出請求,將grant_type指定為password ,我提供用戶憑據以及我的客戶端憑據,我確信他們是用“ php artisanpassport:client --password ”生成的(注意--password選項)
  • 我可以毫無問題地獲得訪問令牌 我現在需要的是獲取我剛剛從 API REST 進行身份驗證的用戶的 JSON 表示。 但問題是:我只有一個訪問令牌 我無法與用戶聯系。

或者我可以嗎? 也許我可以擴展驗證密碼授予請求的方法,將生成的訪問令牌與正在驗證的用戶相關聯...... *燈泡亮起*

使用應用程序測試代碼:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM