2

我使用谷歌API客戶端的谷歌分析使用OAuth 2.0谷歌的OAuth:無法獲取刷新令牌與授權碼

我讀這得到刷新令牌,但不會出現它:https://developers.google.com/identity/protocols/OAuth2WebServer#offline

我只得到這個代替:

{ 
"access_token": "ya29.twHFi4LsiF-AITwzCpupMmie-fljyTIzD9lG8y_OYUdEGKSDL7vD8LPKIqdzRwvoQAWd", 
"token_type": "Bearer", 
"expires_in": 3599, 
"id_token": "very long string" 
} 

下面是代碼:

的Javascript(獲取Authorizat離子碼):的作品

gapi.analytics.ready(function() { 

    gapi.analytics.auth.authorize({ 
     container: 'embed-api-auth-container', 
     clientid: '257497260674-ji56vq885ohe9cdr1j6u0bcpr6hu7rde.apps.googleusercontent.com', 
    }); 

    gapi.analytics.auth.on('success', function(response) { 
     var code = response.code; 
     $.ajax({ 
      url: "getTokensFromCode.php", 
      method: "GET", 
      data: { 
       "code": code 
      }, 
      success: function (tokens) { 
       // I can't get refresh token here, only get "access_token" and "id_token" 
       console.log(tokens); 
      } 
     }); 


    }); 

}); 

PHP(交換授權代碼標記):不起作用

// I get the authorization code in Javascript 
$code = $_GET['code']; 
$redirectURI = "postmessage"; 

$client = new Google_Client(); 
$client->setClientId($clientID); 
$client->setClientSecret($clientSecret); 
$client->setRedirectUri($redirectURI); 
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); 
$client->setAccessType('offline'); 
$client->setApprovalPrompt('force'); 
$client->authenticate($code); 

$tokens = $client->getAccessToken(); 
echo $tokens; 

我需要在JavaScript中刷新令牌,這就是爲什麼我在Javascript中獲得授權代碼併發出Ajax請求來獲取刷新令牌的原因。

回答

1

用戶授予訪問您的應用第一次獲得refresh_token。您需要將refresh_token存儲在某個地方,以便以後可以使用它。下次用戶登錄到您的應用時,您不會獲得新的刷新令牌。在Javascript客戶端中使用刷新令牌沒有什麼意義,因爲Javascript客戶端無法以安全(保密)的方式存儲它。由於Javascript客戶端位於瀏覽器中,並且用戶位於瀏覽器中,因此您可以重新將瀏覽器重定向到授權端點,並且您將獲得新的訪問令牌(這也是刷新令牌的用途)。 Google用戶的SSO會話將確保用戶不需要再次登錄,並且體驗無縫。

+0

我需要授予訪問權限一次,並且無需再次登錄(我需要向我的網站的訪問者顯示數據)而始終獲取分析數據。這就是爲什麼我要'refresh_token'('access_token'只能持續1小時)。 爲了在第一次登錄後獲得'refresh_token',我試過了這個: '$ client-> setAccessType('offline'); $ client-> setApprovalPrompt('force');' – enguerran

+0

我撤銷了訪問並再次登錄,它沒有給我一個'refresh_token'。無論如何,我認爲JS-Ajax-PHP沒有用,我會嘗試一個完整的PHP解決方案,如Google文檔所示。我嘗試過這種方法,因爲我想用Javascript中的'refresh_token',但正如你所說的那樣,反正它不安全。 – enguerran

0

退房由@curious_coder Google API Refresh Token

他解釋的方式來獲取刷新令牌每一次:)生命的救星此響應。這篇文章幫助我到達那裏,所以我想我會分享這個爲其他人試圖找到他們的刷新令牌。這段代碼的最後兩行添加到您的驗證過程

$client = new Google_Client(); 
$client->setAuthConfigFile(__DIR__ . '/client_secrets.json'); 
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/dashboard/oauthcallbacks'); 
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);  
$client->setAccessType('offline'); //To fetch refresh token(Refresh token issued only first time) 
$client->setApprovalPrompt('force'); //Adding this will force for refresh token 

而且我用的var_dump($令牌)來獲得內容,而不是回聲。不要記得它是否會在PHP中有所作爲,但$標記將是一組對象。