如何获取刷新令牌以使用 google api 登录?

时间:2021-04-09 07:10:18

标签: php google-oauth google-api-php-client

首先,我是 google apis 的绝对初学者。我遵循本教程以及网络上的许多其他教程 -> https://www.webslesson.info/2019/09/how-to-make-login-with-google-account-using-php.html 它正在成功运行。但是登录后无法刷新页面,因为我没有刷新令牌。

我的 config.php-

<?php

session_start();
require_once 'vendor/autoload.php';
$google_client = new Google_Client();
$google_client->setClientId('client id here');
$google_client->setClientSecret('client screct here');
$google_client->setRedirectUri('http://localhost/realestate/index.php');
$google_client->addScope('email');
$google_client->addScope('profile');

$google_client->setAccessType('offline');
$google_client->setApprovalPrompt('force');

?>

我的索引文件-

<?php

//Include Configuration File
include('config.php');

$login_button = '';


if(isset($_GET["code"]))
{

$token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);

if(!isset($token['error']))
{

$google_client->setAccessToken($token['access_token']);

$_SESSION['access_token'] = $token['access_token'];

$google_service = new Google_Service_Oauth2($google_client);


$data = $google_service->userinfo->get();


    if(!empty($data['given_name']))
    {
    $_SESSION['user_first_name'] = $data['given_name'];
    }

    if(!empty($data['family_name']))
    {
    $_SESSION['user_last_name'] = $data['family_name'];
    }

    if(!empty($data['email']))
    {
    $_SESSION['user_email_address'] = $data['email'];
    }

        if(!empty($data['gender']))
        {
        $_SESSION['user_gender'] = $data['gender'];
        }

        if(!empty($data['picture']))
        {
            $_SESSION['user_image'] = $data['picture'];
        }
  

    }
}


if(!isset($_SESSION['access_token']))
{

    $login_button = '<a href="'.$google_client->createAuthUrl().'">Login With Google</a>';
}

?>

我问了一个与这个问题有些相关的问题,但这不起作用。所以我又在这里问了,抱歉。

那么,我该如何设置刷新令牌?

1 个答案:

答案 0 :(得分:0)

您确实有一个刷新令牌。问题或谷歌认为你这样做。

当您将其添加到代码中时

$google_client->setAccessType('offline');

它告诉谷歌你想在用户不在线时访问用户数据。 但是,您遇到的问题是,对于某些语言(例如 PHP),Google 会在用户第一次进行身份验证时向您发送刷新令牌,然后他们假设您已将其存储在服务器的某个位置,以便您可以在下一次使用它时间。如果您再次登录用户,您通常不会获得新的刷新令牌,因为他们再次认为您拥有一个。

解决此问题的方法是让用户撤销您的访问权限 revoke。然后下次他们访问您的网站时,应该会提示他们这次登录,您应该有一个刷新令牌。记得把它存放在某个地方,以便下次使用。

此外,当您刷新访问令牌时,请记住检查刷新令牌是否存在,如果不同,则存储新令牌

// Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }