简体   繁体   English

如何在 Laravel 中从 Socialite 和 Google API 客户端获取 id_token

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

I am using socialite to get the user access_token and use that token to get connect to the Google API Client in laravel.我正在使用 socialite 来获取用户 access_token 并使用该令牌连接到 Laravel 中的 Google API 客户端。 Everything is working fine.一切正常。 But I need to get the access token.但我需要获取访问令牌。 But it is failed to get in the response.但它没有得到响应。 Let me know how to get the id_token from Google API client.让我知道如何从 Google API 客户端获取 id_token。

Here is my code这是我的代码

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

This worked for me, using the methods from Laravel's socialite documentation:这对我有用,使用 Laravel 社交名流文档中的方法:

config/services add this to the array (with your own keys) config/services 将此添加到数组中(使用您自己的密钥)

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

Set up your routes as per the docs, and then add these to your class and it will dump out the token and expires_in根据文档设置您的路线,然后将这些添加到您的课程中,它将转储令牌和 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);
}

I had a similar issue where coming from an Android device I didn't have access to the access_token so I had to pass an auth_token instead.我有一个类似的问题,来自 Android 设备我无权访问access_token所以我不得不传递一个auth_token On the server side here's how I handled it to retrieve an access_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