0

我在Java上編寫了可訪問Google驅動器的桌面應用程序。 (它只是上傳和下載文件)。無法使用刷新令牌獲取訪問令牌

目前訪問類型在線。當我需要訪問的文件/文件夾的驅動器,我 他的瀏覽器重定向到URL谷歌並獲得訪問代碼:

String code = "code that was returned from brouser" 
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute(); 
GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response); 

一切正常!但我只需要第一次進行重定向。

當我谷歌,在Google Drive API documentation我發現我可以通過瀏覽器重定向獲取刷新令牌,並將其保存在數據庫中,例如。 (換句話說,我可以使用離線訪問)。

而且每當我需要從谷歌驅動器讀取數據時,我都會使用刷新令牌獲取訪問令牌,而無需重定向。是不是?

,所以我得到刷新令牌這樣的:

https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=695230079990.apps.googleusercontent.com&scope=https://www.googleapis.com/auth/drive&response_type=code&redirect_uri=https://localhost

問題1
我得到的代碼,從瀏覽器重定向。它是更新令牌,不是嗎? 現在,我需要使用該刷新令牌獲取訪問令牌。

$.ajax({ 
     type: "POST", 
     url: 'https://accounts.google.com/o/oauth2/token', 
     data: { 
     client_id: "695230079990.apps.googleusercontent.com", 
     client_secret: 'OWasYmp7YQ...4GJaPjP902R', 
     refresh_toke: '4/hBr......................xwJCgQI', 
     grant_type: 'refresh_token' 
     }, 
     success: function(response) { 
     alert(response); 
     } 

    }); 

,但我有錯誤400;

問題2)當我試圖改變重定向URL我有一個錯誤:*

爲REDIRECT_URI 無效的參數值:非公共領域不允許的:https://sampl.ecom

所以,我必須創建Web應用程序客戶端ID,而不是從谷歌API控制檯安裝的應用程序?我不能在已安裝的應用程序中更改重定向URI嗎?我很困惑,我不知道,應該使用哪一個。

回答

0

1)當您嘗試進行離線訪問時,您將獲得授權碼,該碼可能會被兌換爲訪問令牌和刷新令牌。

對於isntance:

https://accounts.google.com/o/oauth2/auth?access_type=offline 
&approval_prompt=auto 
&client_id=[your id] 
&redirect_uri=[url] 
&response_type=code 
&scope=[access scopes] 
&state=/profile 

你獲得授權碼後,你的貓得到刷新令牌。

static Credential exchangeCode(String authorizationCode) 
     throws CodeExchangeException { 
    try { 
     GoogleAuthorizationCodeFlow flow = getFlow(); 
     GoogleTokenResponse response = 
      flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute(); 
     return flow.createAndStoreCredential(response, null); 
    } catch (IOException e) { 
     System.err.println("An error occurred: " + e); 
     throw new CodeExchangeException(null); 
    } 
    } 

有關更多信息,請參閱Implementing Server-side Authorization標記部分。

當你得到刷新令牌後,你必須保存它。請參閱sample瞭解更多信息。

2)如果您沒有安裝應用程序,則應該創建Web應用程序以更改重定向URL。