gpt4 book ai didi

javascript - Google 登录扩展 token

转载 作者:行者123 更新时间:2023-12-03 11:02:32 25 4
gpt4 key购买 nike

我的问题:

如何接收扩展 token ,以便用户在一小时左右后不会注销?我故意请求离线访问,因为我读到必须这样做才能接收刷新 token 。但我没有在 authResult java 脚本变量中收到它。

<小时/>

我的代码:

这是我的用户使用其 Google 帐户登录我的网站的方式:

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 调用并将访问 token 传递到服务器。

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 函数接收 token 并将其保存在 $_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 - 这是检查 token 是否有效的函数:

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

}
<小时/>

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

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

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

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

其次,我切换到所有 PHP sdk 以接收刷新 token 。

最佳答案

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

The authorization server MUST NOT issue a refresh token.

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

关于javascript - Google 登录扩展 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28019403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com