2017-06-04 76 views
0

以下https://developers.google.com/identity/sign-in/web/server-side-flow從JavaScript獲取授權碼並將其傳遞到服務器端後,我們確實獲得了訪問令牌(和ID令牌),但不是需要刷新令牌。獲取Gmail API訪問和ID令牌,但刷新令牌爲NULL

有很多帖子,但還不能解決它。

任何建議如何獲取刷新令牌?

謝謝!

private String getResponseToken(GoogleClientSecrets clientSecrets, 
               String authCode) throws IOException { 
     try { 
      GoogleTokenResponse tokenResponse = 
        new GoogleAuthorizationCodeTokenRequest(
          new NetHttpTransport(), 
          JacksonFactory.getDefaultInstance(), 
          "https://www.googleapis.com/oauth2/v4/token", 
//      "https://accounts.google.com/o/oauth2/token", 
          clientSecrets.getDetails().getClientId(), 
          clientSecrets.getDetails().getClientSecret(), 

          authCode, //NOTE: was received from JavaScript client 

          "postmessage" //TODO: what's this? 
          ).execute(); 
      String accessToken = tokenResponse.getAccessToken(); 
      String idToken = tokenResponse.getIdToken(); 

      //TODO: not getting a refresh token... why?! 
      String refreshToken = tokenResponse.getRefreshToken(); 
      Boolean hasRefreshToken = new Boolean(!(refreshToken == null)); 
      LOGGER.warn("received refresh token: {}", hasRefreshToken); 

      LOGGER.debug("accessToken: {}, refreshToken: {}, idToken: {}", accessToken, refreshToken, idToken); 
      return accessToken; 
     }catch (TokenResponseException tre){...} 
+0

的可能重複https://stackoverflow.com/questions/10631042/how-to-generate-access-令牌使用刷新令牌通過谷歌驅動器api – noogui

+0

看起來不像重複。實際上,尋找在這篇文章中完成的第一步:「我已完成授權步驟並獲得訪問令牌和刷新令牌。」這就是我們需要的:獲得刷新令牌。其他人在該帖子的底部指出,他在PHP中使用$ client-> setAccessType(「offline」);)。問題是如何使用Java API獲取初始刷新令牌? – Roy

回答

2

Gmail API僅在您首次詢問用戶權限時才提供刷新令牌。 (至少這是發生在我身上的事情)。

轉至:https://myaccount.google.com/permissions?pli=1,刪除您的應用程序的授權並運行您的代碼。您應該收到刷新令牌。

+0

嗨裏卡多,謝謝,但它似乎並沒有解決。刪除應用程序授權將使權限提示再次顯示給用戶,但結果 - 沒有獲得刷新令牌 - 保持不變。 – Roy

0

你應該添加

  1. 接入類型= 「離線」

你需要調用函數

new GoogleAuthorizationCodeRequestUrl(...).setAccessType("offline") 

或另一種語法:

var authReq = new GoogleAuthorizationCodeRequestUrl(new Uri(GoogleAuthConsts.AuthorizationUrl)) { 
    RedirectUri = Callback, 
    ClientId = ClientId, 
    AccessType = "offline", 
    Scope = string.Join(" ", new[] { Scopes... }), 
    ApprovalPrompt = "force" 
}; 

在F iddler你應該看到以下要求:

https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/webmasters&redirect_uri=http://mywebsite.com/google/scapi/callback/&response_type=code&client_id=xxx&ACCESS_TYPE =離線

又見here

更多setAccessType細節可以發現here

0

找到如何在使用谷歌的API後後端(文檔有點偏)..通過調整參數在FrontEnd端修復了問題:

grantOfflineAccess({ - 提示: 'select_account' +提示: '同意'

HTH

相關問題