簡體   English   中英

如何在 Laravel 中從 Socialite 和 Google API 客戶端獲取 id_token

[英]How to get the id_token from Socialite and Google API Client in laravel

我正在使用 socialite 來獲取用戶 access_token 並使用該令牌連接到 Laravel 中的 Google API 客戶端。 一切正常。 但我需要獲取訪問令牌。 但它沒有得到響應。 讓我知道如何從 Google API 客戶端獲取 id_token。

這是我的代碼

public function callback()
    {
        $user = \Socialite::driver('google')->user(); 
        $idToken = $this->getIdToken($user);
        var_dump($idToken);
    }

public function getIdToken($user){
    $google_client_token = [
        'access_token' => $user->token,
        'refresh_token' => $user->refreshToken,
        'expires_in' => $user->expiresIn
    ];

    $client = new Google_Client();
    $client->setAccessToken(json_encode($google_client_token));
    $oauth = new Google_Service_Oauth2($client);

    $client->authenticate($_GET['code']); //exchange 'code' with access token, refresh token and id token
    $accessToken = $client->getAccessToken();
    $userData = $oauth->userinfo->get(); 

    return $userData;
}

這對我有用,使用 Laravel 社交名流文檔中的方法:

config/services 將此添加到數組中(使用您自己的密鑰)

'google' => [
    'client_id' => env('GOOGLE_API_ID'),
    'client_secret' => env('GOOGLE_API_SECRET'),
    'redirect' => env('APP_URL').'/auth/adwords/callback'
],

根據文檔設置您的路線,然后將這些添加到您的課程中,它將轉儲令牌和 expires_in

public function redirectToProvider() {
    return Socialite::with('google')->redirect();
}

public function handleProviderCallback(Request $request) {
    $adwords_api_response = Socialite::with('google')->getAccessTokenResponse($request->code);

    dd($adwords_api_response);
}

我有一個類似的問題,來自 Android 設備我無權訪問access_token所以我不得不傳遞一個auth_token 在服務器端,這是我如何處理它以檢索access_token

  $driver = Socialite::driver('google');
  //In some cases coming from android an auth token may be required to get an access token 
  $access_token = $driver->getAccessTokenResponse($input['auth_token'])['access_token'];
  $googleUser = $driver->userFromToken($access_token);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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