在 Google OAuth 2.0 中使用适当的参数进行首次身份验证时未获得刷新令牌 null

Not getting refresh token, null, on first auth with proper parameters in Google OAuth 2.0

我正在使用 Google O Auth 2.0 PHP API 客户端库来授权我的应用程序并获取访问令牌和刷新令牌。我确实获得了访问令牌。

返回的 JSON 有 access_token、token_type、过期和 id_token,我相信,但它没有 refresh_token .

我尝试只获取库中的 refresh_token,但我得到的是 NULL。

这是第一次授权,因为我在我的 url 重定向中使用了 prompt=consent 参数,并且我在每次执行此操作之前都在 Google 帐户控制台中手动拒绝我的应用程序,仍然没有获得刷新令牌。

这是我成功获取访问令牌但没有刷新令牌的代码:

$client = new Google_Client();
$client->setAuthConfig('php/client_secret.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope(array('email', 'profile', 'calendar'));
$token=$client->fetchAccessTokenWithAuthCode(urldecode($authCode));

这是我的代码,returns 刷新令牌为空:

$client = new Google_Client();
$client->setAuthConfig('php/client_secret.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope(array('email', 'profile', 'calendar'));
$client->authenticate(urldecode($authCode));
$token=$client->getRefreshToken();

我希望能在这里阐明一些问题。我不确定我是否正确理解了您的实现,但我就是这样做的。

<?php session_start(); 

//INCLUDE PHP CLIENT LIBRARY
require_once 'vendor/autoload.php';

// Create client object
$client = new Google_Client(); 
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/Test.php');
$client->setAuthConfig("client_secret.json");
$client->addScope(array('email', 'profile'));
$client->setAccessType('offline');
$client->setApprovalPrompt('force');

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

  $authUrl = $client->createAuthUrl();
  header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));

} else {

  $authCode = $_GET['code'];
  $token = $client->fetchAccessTokenWithAuthCode(urldecode($authCode));

  var_dump($token);

}

?>

这是我在 运行 上面的脚本之后得到的:

array (size=6)
  'access_token' => string 'ya29.-r76enex2-m8QUZv-kdRwV4huHSC-' (length=129)
  'token_type' => string 'Bearer' (length=6)
  'expires_in' => int 3599
  'refresh_token' => string '1/T8z2Gw78wporTviu3In8' (length=45)
  'id_token' => string 'eyJhbGciOiJIsImtpZCc4M2VkMGMifQ.'... (length=1209)
  'created' => int 1488420909

我注意到如果我使用 $client->addScope(array('email', 'profile', 'calendar'));,我会收到一个错误,所以我删除了 calendar。据我了解,当您使用 $client->setAccessType('offline');$client->setApprovalPrompt('force'); 时,系统会提示您允许离线访问,如果您单击 "Allow",您应该会像我一样获得刷新令牌。