谷歌登录扩展令牌

Google sign in extended token

本文关键字:令牌 扩展 登录 谷歌      更新时间:2023-09-26

我的问题:

我如何接收扩展令牌,以便用户在一个小时左右后不会注销?我有意请求脱机访问,因为我读到必须这样才能接收刷新令牌。但是我在authResultjava脚本变量中没有收到它。


我的代码:

这就是我的用户如何使用他们的谷歌帐户登录我的网站:

1-显示登录按钮。

<span id="signinButton">
    <span class="g-signin" data-callback="signinCallback" data-clientid="********.apps.googleusercontent.com" data-access_type="offline" data-cookiepolicy="single_host_origin" data-requestvisibleactions="http://schema.org/AddAction" data-scope="https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read https://www.googleapis.com/auth/offline"></span>
</span>

2-用户单击按钮后,将进行ajax调用,并将访问令牌传递给服务器。

function signinCallback(authResult) {
  if (authResult['status']['signed_in']) {
    //Shoot the ajax
    $.ajax({
        //...Send the access token to the server
    })
        .done(function(msg) {
            //...Do somthing after a sucessfull login
        });
  } else {
    //...
  }
}

3-一个PHP函数接收令牌并将其保存在$_SESSION变量中以备以后使用。

public function GoogleAuth($token) {
    $_SESSION['google_token'] = $token;
    #See that the token is valid
    $session_status = $this->GetSessionStatus($token, 'all');
    if ($session_status == false) {
        return $session_status;
    }
    #If token is valid, manage the registration/login process
    //...
}

4-以下是检查令牌是否有效的功能:

public function GetSessionStatus($token) {
    $url = 'https://www.googleapis.com/oauth2/v1/userinfo';
    $params = 'access_token='.$token;
    $ch = curl_init($url . '?' . $params);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
    if (!empty($headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POST, false);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $user = curl_exec($ch); 
    $user = json_decode($user);
    curl_close($ch);
    if (isset($user->id)) {
        return true;
    } else {
        return false;
    }
}

再次提出我的问题,以防您忘记:(

这就是我处理登录的方式。我不确定我做得是否正确,但它有效。我的问题是如何接收扩展令牌,这样用户在一个小时左右后就不会注销。我故意请求离线访问,因为我读到必须这样才能接收刷新令牌。但是我在authResultjava脚本变量中没有收到它。

编辑:最后(如何解决(:

首先,我使用的不是$_SESSION,而是$_COOKIE。它更持久。

第二,我切换到所有的PHP sdk,以便接收刷新令牌。

使用Javascript意味着您正在使用所谓的OAuth 2.0隐式授予,并且由于安全限制,该授予类型无法返回刷新令牌。规范在第节中说明https://www.rfc-editor.org/rfc/rfc6749#section-4.2.2:

授权服务器不得发布刷新令牌。

这是因为Javascript客户端无法安全地存储长寿命令牌。最好使用服务器端流,例如使用google-api-php-client,这样您也可以以安全的方式存储和重用刷新令牌。