2017-01-20 38 views
1

我使用Google OAuth 2.0爲服務器端Web應用程序使用PHP 5.4.45和Google API Client PHP Library 2.1.1版。PHP中缺少Google ID令牌的信息

我能成功地與refresh_tokenaccess_tokenid_token交換authorization code,我可以正確地驗證id_token並從中提取用戶的數據,但某些信息丟失。

我要求profileemail範圍,這都得到正確顯示在同意畫面,並在用戶的應用程序的設置,但是,當郵箱服務,與profile範圍相關的所有要求從id_token失蹤(名,圖片等)。

我嘗試過不同的用戶,問題依然存在。

這是我使用的代碼(只是用於測試):

require_once 'php/libs/google_api_client_library/vendor/autoload.php'; 

if(!isset($_GET['code'])){ 
    die("code parameter not set"); 

}else{ 
    //exchange 'code' with access token, refresh token and id token 
    $data = array(
     'code' => $_GET['code'], 
     'client_id' => $MY_CLIENT_ID, 
     'client_secret' => $MY_CLIENT_SECRET, 
     'redirect_uri' => 'https://www.mywebsite.com/oauth2callback.php', 
     'grant_type' => 'authorization_code' 
    ); 
    $options = array(
     'http' => array(
      'header' => "Content-type: application/x-www-form-urlencoded\r\n", 
      'method' => 'POST', 
      'content' => http_build_query($data) 
     ) 
    ); 
    $response = file_get_contents('https://accounts.google.com/o/oauth2/token', false, stream_context_create($options)); 

    if($response){ 
     $tokens = json_decode($response); 

     $client = new Google_Client(); 

     //validate idToken and get user info 
     $idtoken = $client->verifyIdToken($tokens->id_token); 

     echo "<h1>ID_TOKEN</h1>"; 
     var_dump($idtoken); 
    } 
} 

最奇怪的是,它使用前正常工作,然後突然開始表現得像是,和我不不記得對這段代碼做任何修改。

我還注意到,這隻發生在服務器端,使用PHP,因爲JavaScript API客戶端庫的一切都很好。

爲什麼會發生這種情況的任何想法?

讓我知道如果您需要任何進一步的信息,並提前致謝!

+0

你試過了什麼? –

+0

我嘗試過在線和離線使用不同的Google帳戶'access_type',但沒有任何更改。 我也嘗試在查詢字符串中包括'fetch_basic_profile = true',並在'scopes'中包含'openid',因爲我在一些例子中看到了它,但沒有運氣。 我還檢查了從PHP庫中提取的id_token數據與Google的tokeninfo端點返回的數據相同。 –

回答

0

我不知道究竟是問題,但隨着一些例子我已經我用Google_Service_Oauth2類和編輯我的代碼如下發現在互聯網上的幫助:

require_once 'php/libs/google_api_client_library/vendor/autoload.php'; 

if(!isset($_GET['code'])){ 
    die("code parameter not set"); 

}else{ 
    $client = new Google_Client(); 
    $client->setClientId($MY_CLIENT_ID); 
    $client->setClientSecret($MY_CLIENT_SECRET); 
    $client->setApplicationName('MyApplicationName'); 
    $client->setRedirectUri('https://www.mywebsite.com/oauth2callback.php'); 
    $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(); //get user info 

    echo "<h1>USER DATA</h1>"; 
    var_dump($userData); 
} 

而現在一切正常正好!