php - 在 Gmail API 上使用刷新 token 。跟踪旧 key

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

TL;DR

这里的问题是,如果不先执行setAccessToken(),并且为了执行setAccessToken(),我就无法执行fetchAccessTokenWithRefreshToken()我需要知道以前的访问 token 。

如果我在没有先调用 setAccessToken() 的情况下尝试fetchAccessTokenWithRefreshToken(),我会收到“LogicException:刷新 token 必须传入或设置为 setAccessToken 的一部分”

如果我尝试仅使用 refresh_token 值来 setAccessToken(),它也会失败,并出现无效的 token 格式

它的唯一工作方式是提供完整的有效身份验证 token 包,而不仅仅是刷新 token 。

我使用此脚本来获取第一次身份验证并生成刷新 token :

<?php
require __DIR__ . '/vendor/autoload.php';

$client = new Google_Client();

$client->setApplicationName('Gmail API Generate Refresh Token');
$client->setScopes(Google_Service_Gmail::GMAIL_MODIFY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');

// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));

// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
if (array_key_exists('error', $accessToken)) {
    throw new Exception(join(', ', $accessToken));
}
print "\n\nBelow is the refresh token.\n\n";
print "Use this token with an authenticated Google_Client object to refresh auth tokens.\n";
print "This string MUST be saved otherwise you will need user approval again\n\n";
print $client->getRefreshToken();

file_put_contents('token.json', json_encode($client->getAccessToken()));
print "\n\nThe first auth token bundle has been saved to token.json\n";

概述

  • 我有一个功能齐全的服务器端应用程序,用于与单个用户的 Gmail 收件箱进行交互。
    • 我拥有 API 凭证,并且刷新 token 保存在持久安全存储中。
    • 应用程序可以成功与 Gmail 交互,直到访问 token 过期。

Overall the goal here is to be able to interact with the Gmail API when the application has ONLY the following: valid client id/secret, and a refresh_token. What I'm finding is that I need to keep track of the auth tokens as well as the refresh token.

这是我面临的问题:

  • 访问 token 过期后,我无法仅使用 API 凭据和刷新 token 生成新的访问 token 。
  • 如果我尝试仅使用刷新 token 字符串作为参数来调用 fetchAccessTokenWithRefreshToken(),则会收到错误 invalid_grant
  • 我可以让它为我提供新 token 的唯一方法是提供刷新 token 和当前访问 token 信息!
    • 我不仅需要原始访问 token 本身,还需要 createdexpires_in 值。

I have to pass it a full array of info: [access_token, expires_in, created, refresh_token] otherwise it simply won't work!

显然我在这里做错了,我认为我需要的只是刷新 token 来根据需要生成访问 token 。


[PHP] 以下是一些片段:

(请注意,这些仅用于开发,我不打算在代码中硬编码 secret )

这是我“期望”起作用的(这不起作用): 这里的错误是invalid_grant

    $client = new Google_Client();
    $client->setApplicationName('Gmail API PHP Quickstart');
    $client->setScopes(Google_Service_Gmail::GMAIL_MODIFY);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // This is the REFRESH token
    $token = '1\/\/0dKcfaketokentokentokenfaketoken-L9IriuoNveLzVQ1w4-lPfakeEPn1R1NjcOK2ISE--O1PO1yEtokenr87E';

    // var_dump just for sanity to ensure this returns true
    var_dump($client->isAccessTokenExpired());

    if ($client->isAccessTokenExpired()) {
      var_dump($client->fetchAccessTokenWithRefreshToken($token));
    }

这有效,因为我向它提供了完整的 $token 数组(或者是因为我事先预先提供了 setAccessToken() 。:

    $token = array();
    $token['access_token'] = '<<SCRUBBED_CURRENT_ACCESS_TOKEN>>>';
    $token['expires_in'] = 3599;
    $token['refresh_token'] = '<<SCRUBBED_REFRESH_TOKEN>>';
    $token['created'] = 1587447211;

    // If I leave out ANY of the values above, the token refresh does not work! 

    // omitted some Gmail client configuration and setup. 

    $this->client->setAccessToken($token);

    if ($this->client->isAccessTokenExpired()) {
      $this->accessToken =  $this->client->fetchAccessTokenWithRefreshToken($token);
    }
    else {
      $this->accessToken = $this->client->getAccessToken();
    }
    $this->service = new Google_Service_Gmail($this->client);

线索:

I noticed on https://github.com/googleapis/google-api-php-client/blob/1fdfe942f9aaf3064e621834a5e3047fccb3a6da/src/Google/Client.php#L275 The fetchAccessTokenWithRefreshToken() will fall back to the existing token, this explains why it'll work when I pre-set an existing token. At least that mystery seems to be solved. Does not explain why it's still not working without a pre-set token.

我希望它能像这样工作:

    // Omitted initial Gmail client setup

    if ($this->client->isAccessTokenExpired()) {
      $this->accessToken =  $this->client->fetchAccessTokenWithRefreshToken('<MY_REFRESH_TOKEN');
    }
    else {
      $this->accessToken = $this->client->getAccessToken();
    }
    $this->service = new Google_Service_Gmail($this->client);

这也不起作用(确认 getRefreshToken() 值很好):

$this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());

最佳答案

invalid_grant

表示您正在使用的 token 无效或已过期,或者您正在尝试使用有效的刷新 token ,其客户端 ID 和 key 未用于创建它。在这种情况下,您正在发送一个对象,并且应该只在那里发送有效的刷新 token ,因为您发送到该方法的值不正确。

fetchAccessTokenWithRefreshToken方法采用刷新 token 而不是对象。只需向其传递刷新 token 即可。

示例:ClientTest.php#L485

客户端创建

$client = new Google_Client();
$client->setAccessType("offline");        // offline access.  Will result in a refresh token
$client->setIncludeGrantedScopes(true);   // incremental auth
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope([YOUR SCOPES HERE]);
$client->setRedirectUri(getRedirectUri());  

检查是否过期并根据需要刷新。

if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());      
    }

注意

如果您要获取由另一个脚本保存和创建的刷新 token ,则刷新 token 的系统必须使用相同的客户端 ID 和客户端 key IE (client_secrets.json),以便能够使用它来刷新访问。它不能只是同一项目中的另一个,它必须是相同的 secret 。

also see Oauth2Authencation.php

将 token 保存到文件夹的完整示例

oauth2callback.php

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';

// Start a session to persist credentials.
session_start();

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
    $client = buildClient();
    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
    $client = buildClient();
    $client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
    // Add access token and refresh token to seession.
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();    
    //Redirect back to main script
    $redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());    
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

Oauth2Authentication.php

require_once __DIR__ . '/vendor/autoload.php';
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    $client = getOauth2Client();

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

/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Scopes will need to be changed depending upon the API's being accessed.
 * Example:  array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function buildClient(){
    
    $client = new Google_Client();
    $client->setAccessType("offline");        // offline access.  Will result in a refresh token
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope([YOUR SCOPES HERE]);
    $client->setRedirectUri(getRedirectUri());  
    return $client;
}

/**
 * Builds the redirect uri.
 * Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
 * Hostname and current server path are needed to redirect to oauth2callback.php
 * @return A redirect uri.
 */
function getRedirectUri(){

    //Building Redirect URI
    $url = $_SERVER['REQUEST_URI'];                    //returns the current URL
    if(strrpos($url, '?') > 0)
        $url = substr($url, 0, strrpos($url, '?') );  // Removing any parameters.
    $folder = substr($url, 0, strrpos($url, '/') );   // Removeing current file.
    return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}


/**
 * Authenticating to Google using Oauth2
 * Documentation:  https://developers.google.com/identity/protocols/OAuth2
 * Returns a Google client with refresh token and access tokens set. 
 *  If not authencated then we will redirect to request authencation.
 * @return A google client object.
 */
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();
    }
}

注意:刷新 token 仅保证在用户第一次同意您访问他们的数据时在第一次调用时返回,谷歌假设您已经存储了刷新 token ,因此他们不会发送新的 token 。这就是为什么系统使用存储的刷新 token 自动刷新访问 token 后,只再次保存访问 token 。

关于php - 在 Gmail API 上使用刷新 token 。跟踪旧 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61336881/

相关文章:

php - MYSQL SELECT 在同一个表中包含 COUNT 并引用特定列

google-analytics - 从Google Analytics(分析)向Power Query添加列

android - 我想从我的 Android watch 向我的 Android 手机发送消息。其他方式正在工作

google-analytics - 无法将用户添加到帐户。用户已达到其 Google Analytics(分析)帐户的最大数量

ios - 在 objective-c 中刷新 Gmail API 访问 token 的正确方法

ajax - MVC 5 OAuth 与 CORS

php - 如何使用pdo从sql中删除数据?

php - mysqli_connect() : php_network_getaddresses: getaddrinfo failed: Name or service not known

php - 连接 R 和 PHP

google-api - gdata 未知授权 header - 13 年 12 月 11 日开始