2014-10-28 59 views
0

我在尋找一種驗證Google日曆的方法。目前,我們編寫應用程序的方式包括生成身份驗證URL,並讓用戶導航到該URL並將「成功代碼」複製並粘貼到程序中,然後輸入該身份驗證令牌以進行處理。Java:Google日曆身份驗證

我正在尋找一種方法來自動化該過程:使我們的應用程序直接讀取用戶瀏覽器窗口中生成的成功代碼。這消除了用戶手動複製和粘貼代碼的需要。

希望能得到關於如何實現這樣一個功能的指導,以及我應該使用哪些庫或者任何特定的方法來實現這一點。

這是產生用於用戶導航到一個URL的方法中,並返回此URL:

public static String generateNewTokenStep1() { 


     HttpTransport httpTransport = new NetHttpTransport(); 
     JsonFactory jsonFactory = new JacksonFactory(); 

     // Create the authorization code flow manager 
     Set<String> scope = Collections.singleton(CalendarScopes.CALENDAR); 
     String clientId = "_______"; 
     String clientSecret = "__________"; 


     AuthorizationCodeFlow.Builder codeFlowBuilder = new GoogleAuthorizationCodeFlow.Builder(
       httpTransport, jsonFactory, clientId, clientSecret, scope); 
     codeFlow = codeFlowBuilder.build(); 


     String userId = USER_ID; 

     // "redirect" to the authentication url 
     redirectUri = "urn:ietf:wg:oauth:2.0:oob"; 
     AuthorizationCodeRequestUrl authorizationUrl = codeFlow 
       .newAuthorizationUrl(); 
     authorizationUrl.setRedirectUri(redirectUri); 

     return authorizationUrl.toString(); 

    } 

這是發生在由谷歌產生的成功代碼的方法。

public static String generateNewTokenStep2(String userInput) { 

     String code = userInput; 
     AuthorizationCodeTokenRequest tokenRequest = codeFlow 
       .newTokenRequest(code); 

     tokenRequest.setRedirectUri(redirectUri); 
     TokenResponse tokenResponse = null; 
     try { 
      tokenResponse = tokenRequest.execute(); 
     } catch (IOException tokenRequestFailed) { 
      System.err.println("Token request failed"); 
     } 
     System.out.println(tokenResponse.getAccessToken()); 
     addToDb(tokenResponse.getAccessToken()); 

     return tokenResponse.getAccessToken(); 
    } 
+0

您是否可以選擇使用redirect_uri來獲得對所需端口或Web服務器的響應? https://developers.google.com/accounts/docs/OAuth2InstalledApp#choosingredirecturi – luc 2014-10-29 23:32:48

回答

0

您可以通過使用AuthorizationCodeInstalledApp得到Credential做到這一點。以下示例代碼從Google+ command line sample複製而來。它使用類似的認證流程,除非它創建了一個LocalServerReceiver,它偵聽並接收代碼,因此用戶不必執行任何手動步驟。

// Set up the HTTP transport and JSON factory 
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); 
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); 

// Load client secrets 
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, 
    new InputStreamReader(PlusSample.class.getResourceAsStream("/client_secrets.json"))); 

// Set up authorization code flow 
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
    httpTransport, jsonFactory, clientSecrets, 
    Collections.singleton(PlusScopes.PLUS_ME)).setDataStoreFactory(dataStoreFactory) 
    .build(); 

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