Php GMail访问令牌每一小时过期一次,刷新令牌不工作
我有一个来自oauth authentication的token.json文件来访问gmail apiPhp GMail访问令牌每一小时过期一次,刷新令牌不工作,php,google-api,google-oauth,gmail-api,Php,Google Api,Google Oauth,Gmail Api,我有一个来自oauth authentication的token.json文件来访问gmail api { "access_token":"token", "expires_in":3599, "refresh_token":"token", "scope":"https:\/\/mail.google.com\/ https:\/\/www.
{
"access_token":"token",
"expires_in":3599,
"refresh_token":"token",
"scope":"https:\/\/mail.google.com\/ https:\/\/www.googleapis.com\/auth\/gmail.compose",
"token_type":"Bearer",
"created":1615956208
}
下面是我的代码
Class Connection extends CI_Controller {
public function __construct() {
// echo .'contruct';
// die;
// parent::__construct();
$this->credentials = "assets/gmail_api/credentials/credentials.json";
$this->client = $this->create_client();
}
public function get_client() {
return $this->client;
}
public function get_credentials() {
return $this->credentials;
}
public function is_connected() {
return $this->is_connected;
}
public function get_unauthenticated_data() {
$authUrl = $this->client->createAuthUrl();
return "<a href='".$authUrl."'>Click to Link Your Gmail</a>";
}
public function credentials_in_browser() {
if (isset($_GET['code'])) {
return true;
}
return false;
}
public function create_client() {
$client = new Google_Client();
$client->setApplicationName('Gmail API PHP Quickstart');
$client->setScopes(array(
'https://mail.google.com/',
'https://www.googleapis.com/auth/gmail.compose'
));
$client->setAuthConfig($this->credentials);
$client->setAccessType('offline');
$client->setPrompt('consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'assets/gmail_api/'.$_SESSION['mail_box_email'].'/token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
elseif ($this->credentials_in_browser()) {
$authCode = $_GET['code'];
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
else {
$this->is_connected = false;
return $client;
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
else {
$this->is_connected = true;
return $client;
}
$this->is_connected = true;
return $client;
}
}
类连接扩展CI\U控制器{
公共函数构造(){
//回声“构造”;
//死亡;
//父项::_构造();
$this->credentials=“assets/gmail\u api/credentials/credentials.json”;
$this->client=$this->create_client();
}
公共函数get_client(){
返回$this->client;
}
公共函数get_credentials(){
返回$this->credentials;
}
公共功能已连接(){
返回$this->已连接;
}
公共函数获取未经验证的数据(){
$authUrl=$this->client->createAuthUrl();
返回“”;
}
浏览器()中的公用函数凭据{
如果(isset($_GET['code'])){
返回true;
}
返回false;
}
公共函数create_client(){
$client=新的Google_客户端();
$client->setApplicationName('Gmail API PHP Quickstart');
$client->setscope(阵列)(
'https://mail.google.com/',
'https://www.googleapis.com/auth/gmail.compose'
));
$client->setAuthConfig($this->credentials);
$client->setAccessType('offline');
$client->setPrompt(“同意”);
//从文件加载以前授权的令牌(如果存在)。
//文件token.json存储用户的访问和刷新令牌,并且
//在第一次完成授权流时自动创建
//时间。
$tokenPath='assets/gmail_api/'。$会话['mail_box_email']./token.json';
如果(文件_存在($tokenPath)){
$accessToken=json_decode(file_get_contents($tokenPath),true);
$client->setAccessToken($accessToken);
}
//如果没有以前的令牌或它已过期。
如果($client->isAccessTokenExpired()){
//如果可能,请刷新令牌,否则请获取新令牌。
如果($client->getRefreshToken()){
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
elseif($this->credentials\u in\u browser()){
$authCode=$_GET['code'];
//交换访问令牌的授权代码。
$accessToken=$client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
//检查是否有错误。
如果(数组\密钥\存在('error',$accessToken)){
抛出新异常(join(“,”,$accessToken));
}
}
否则{
$this->is_connected=false;
返回$client;
}
//将令牌保存到文件中。
如果(!file_存在(dirname($tokenPath))){
mkdir(dirname($tokenPath),0700,true);
}
文件内容($tokenPath,json_encode($client->getAccessToken());
}
否则{
$this->is_connected=true;
返回$client;
}
$this->is_connected=true;
返回$client;
}
}
这是我的刷新令牌
我搜索了oauth访问令牌,它总是在1小时内过期,但我想尽可能延长这段时间,所以我使用refresh token,这里我的token.json文件有refresh token,但它仍然在1小时内过期,我读过google oauth文档,他们说refresh token的最长生存时间是200天()
如何增加访问令牌的生存时间,我真的不明白它是如何工作的,请给出一些延长访问令牌生存时间的解决方案
谢谢。访问令牌在一小时后过期这是所有授权服务器的标准配置。这是你无法改变的 您应该做的是在需要时使用刷新令牌来请求新的访问令牌。刷新令牌在大多数情况下不会过期,但是gmail api作用域有一些技巧,如果用户更改密码,它将过期
https://accounts.google.com/o/oauth2/token
client_id={ClientId}&client_secret={ClientSecret}&refresh_token={refreshtoken}&grant_type=refresh_token
如果您使用的是php客户机库,那么您不需要处理这些问题,所有这些都应该为您处理
我给您的代码是使用刷新令牌并将其取回访问令牌的实际调用。由于您没有发布代码,我无法告诉您如何在代码中使用它。如果您正在使用PHP客户端库,那么这可能会有帮助,看起来您已经在使用刷新令牌了。访问令牌将使If($client->isAccessTokenExpired())所在的部分过期{将使用有效的刷新令牌获取新的访问令牌。请尝试我刚才发布的两个文件。这是我为Gmail api提供的示例代码。它显示了如何使用刷新令牌,但它将它们存储为会话变量。您还可以将它们与用户id一起存储在数据库中,以便知道刷新令牌是谁。$client->setAuthConfig(DIR.'/client_secrets.json');
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();
}
}
?>
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));
}
?>