我正在将Gmail OAuth2集成到Suite CRM中。我本地的一切都运行得很好。我在第一次API调用时获得了刷新令牌,但在生产环境中,我获得了令牌/访问令牌,但获得了一个空的刷新令牌。这是否与某些Gmail权限有关,这些权限允许我的生产应用程序,并允许我的本地应用程序或其他什么?
参考代码:
$params = [
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'redirectUri' => $redirectUri,
'accessType' => 'offline',
];
$options = [];
session_start();
$provider = new Google($params);
$options = [
'scope' => [
'https://mail.google.com/'
]
];
if (null === $provider) {
exit('Provider missing');
}
if (!empty($_GET['error'])) {
// Got an error, probably user denied access
exit('Got error: ' . htmlspecialchars($_GET['error'], ENT_QUOTES, 'UTF-8'));
}
if (!isset($_GET['code'])) {
// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl($options);
$_SESSION['oauth2state'] = $provider->getState();
header('Location: ' . $authUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
unset($_SESSION['provider']);
exit('Invalid state');
} else {
// unset($_SESSION['provider']);
$token = $provider->getAccessToken(
'authorization_code',
[
'code' => $_GET['code']
]
); //Gets Token
$refresh_token = $token->getRefreshToken(); // Get Null in response
// Use this to interact with an API on the users behalf
$access_token = $token->getToken(); //access token
// Unix timestamp at which the access token expires
$access_tkn_expiration = $token->getExpires(); //access token expiry发布于 2020-11-19 17:53:21
对于一些语言,主要是基于web的脚本语言,Google不会每次都返回新的刷新令牌。它们假定您已经保存了刷新令牌。
要强制一个新的访问令牌,您可以对用户访问令牌执行撤销操作,这将导致用户撤销您对其数据的访问权限。然后,下次用户登录时,系统将提示他们授予您访问权限,您应该会获得一个新的刷新令牌。
所有这些都假设您正在请求offline作用域,而我在您的代码中看不到它。
function getOauth2Client() {
try {
$client = buildClient();
// Set the refresh token on the client.
if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
$client->refreshToken($_SESSION['refresh_token']);
}
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
return $client;
} else {
// We do not have access request access.
header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
}
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}https://stackoverflow.com/questions/64909027
复制相似问题