2016-08-02 18 views
2

爲了讓Java程序來訪問我的谷歌驅動器,我需要使用JSON證書文件來創建oauth2.Credential(見https://console.developers.google.com)用於獲取一個訪問令牌。獲得從Java程序打開的瀏覽器谷歌授權要求已獲准

Credentials with client id

問題是,當我創建了憑據Java實例Java程序打開Internet Explorer,並要求許可驅動器。

Credential credential = new AuthorizationCodeInstalledApp(flow 
       , new LocalServerReceiver()) 
       .authorize("user") 
       ; 

Program automatically opens browser and ask permission

如果我點擊按鈕 「允許」,將創建憑證和我得到的令牌。

System.out.println("token" + credential.getAccessToken()); 

Browser after clicked on Allow

Java console view in Eclipse : token get

的問題是,這個java程序將是一個批處理程序,所以我們不能要求批量點擊一個按鈕。

此外,在https://security.google.com/settings/security/permissions?pli=1我的硬盤已經獲准進入我的應用程序(應用程序名稱是GoogleTest)...

application already granted

你知道如何讓沒有java程序打開的瀏覽器證書詢問許可? 謝謝

這裏全碼:

public static void getToken() { 
    HttpTransport httpTransport ; 
    InputStream inputStream;  
    try { 
     httpTransport = GoogleNetHttpTransport.newTrustedTransport(); 
     List<String> scope = Arrays.asList(DriveScopes.DRIVE); 
     inputStream = new FileInputStream("C:/dev/ws/mainAzure/GoogleTest/res/client_secret_jcb_inst.json"); 
     InputStreamReader reader = new InputStreamReader(inputStream); 
     clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,reader);        
     GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      httpTransport 
      , JSON_FACTORY 
      ,clientSecrets 
      , scope) 
      .setAccessType("offline") 
      .setApprovalPrompt("force") 
      .build();     

     //Browser open when there is new AuthorizationCodeInstalledApp(...) 
     Credential credential = new AuthorizationCodeInstalledApp(flow 
      , new LocalServerReceiver()) 
      .authorize("user") 
      ; 
    System.out.println("token" + credential.getAccessToken()); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

回答

2

經過一定的幫助(謝謝哈羅德)我可以找到解決方案: 一個需要定義一個數據庫工廠,其他地方的refreshToken不存儲在一個文件中,谷歌通過互聯網瀏覽器每次都要求權限。 於是我說:

dataStoreFactory = new FileDataStoreFactory(new File("C:/dev/ws/mainAzure/GoogleTest/res")); 

和:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      httpTransport 
      , JSON_FACTORY 
      ,clientSecrets 
      , scope) 
      .setAccessType("offline") 
      .setApprovalPrompt("force") 
      .build(); 

成爲:

  flow = new GoogleAuthorizationCodeFlow.Builder(
       httpTransport 
       , JSON_FACTORY 
       ,clientSecrets 
       , scope)      
       .setAccessType("offline") 
       .setDataStoreFactory(dataStoreFactory) 
       .setApprovalPrompt("force")     
       .build(); 

而且有不超過1小時,一個需要訪問刷新令牌:

credential.refreshToken() ; 
1

這對你的授權碼流。只要您訪問同一個Google帳戶,即可重新使用相同的憑據。

考慮使用刷新令牌手動獲取訪問代碼,並手動將其輸入批處理代碼。

+0

謝謝您的回答,但目標是讓程序從谷歌驅動器訪問數據,而無需手動干預注入訪問令牌。我正在尋找解決方案。你認爲無法自動獲取令牌嗎? –

+0

查看Google API的已安裝應用程序流程。我認爲這就是你所需要的 –

+3

這個操作只需要在程序的安裝過程中執行一次,一旦刷新標記被存儲,它不會再被詢問,批處理將使用刷新標記來再次獲得新的訪問標記,再次。 – Harold