簡體   English   中英

PHP 中缺少來自 Google ID 令牌的信息

[英]Missing information from Google ID Token in PHP

我將 Google OAuth 2.0 用於我的服務器端 Web 應用程序,帶有 PHP 5.4.45 和 Google API 客戶端 PHP 庫版本 2.1.1。

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

我請求了profileemail范圍,它們都在同意屏幕和用戶的應用程序設置中正確顯示,但是,雖然電子郵件可用,但 id_token(姓名、圖片等)中缺少與profile范圍相關的所有聲明……)。

我嘗試了不同的用戶,但問題仍然存在。

這是我正在使用的代碼(僅用於測試目的):

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 客戶端庫一切正常。

為什么會發生這種情況的任何想法?

如果您需要任何進一步的信息,請告訴我,並提前致謝!

我不知道到底是什么問題,但是在我在互聯網上找到的一些示例的幫助下,我使用了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);
}

現在一切正常!

暫無
暫無

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

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