2013-12-11 108 views
0

我嘗試使用OAuth 2.0從本機應用程序訪問Google端點服務。我設法使用GoogleAuthorizationCodeFlow和JavaFX webview(作爲瀏覽器)進行身份驗證。 成功驗證後,我嘗試訪問API方法,但用戶對象始終爲空,問題是爲什麼?Google端點:從本機客戶端訪問認證api

代碼API方法調用:

GoogleAuthorizationCodeFlow flow = getGoogleAuthorizationCodeFlow(); 
Credential credential = flow.loadCredential(USER_ID); 
Helloworld.Builder builder = new Helloworld.Builder(new NetHttpTransport(), 
               new JacksonFactory(), credential); 
Helloworld service = builder.build(); 
Helloworld.Greetings.Authed protectedApiMethod = service. 
              greetings().authed(); 
HelloGreeting execute = protectedApiMethod.execute(); 
System.out.println("Response " + execute.getMessage()); 

代碼創建流對象:

private static GoogleAuthorizationCodeFlow getGoogleAuthorizationCodeFlow() { 
    return new GoogleAuthorizationCodeFlow(new NetHttpTransport(), 
     new JacksonFactory(), INSTALLED_ID, CLIENT_SECRET, Arrays.asList(SCOPE_EMAIL)); 
} 

代碼,我嘗試驗證:

GoogleAuthorizationCodeFlow flow = getGoogleAuthorizationCodeFlow(); 
GoogleAuthorizationCodeTokenRequest tokenRequest = flow.newTokenRequest(code); 
tokenRequest.setRedirectUri(REDIRECT_URL); 
    try { 
     GoogleTokenResponse execute = tokenRequest.execute(); 
     flow.createAndStoreCredential(execute, USER_ID); 
     Platform.exit(); 
    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 
} 

API方法的聲明:

@ApiMethod(name = "greetings.authed", 
      path = "greeting/authed", 
      clientIds = {Constants.WEB_CLIENT_ID, Constants.INSTALLED_ID,  
       Constants.API_EXPLORER_CLIENT_ID}) 
public HelloGreeting authedGreeting(User user) { 
    if (user != null) { 
     HelloGreeting response = new HelloGreeting("hello " + user.getEmail()); 
     return response; 
    } else { 
     HelloGreeting response = new HelloGreeting("no user object was specified"); 
     return response; 
    } 
} 

我得到的唯一答案是「沒有指定用戶對象」。由於我可以調用方法沒有任何錯誤,我想我的身份驗證正確。

回答

0

從文檔:https://developers.google.com/appengine/docs/java/endpoints/getstarted/backend/auth

如果來自客戶端的請求具有有效的身份驗證令牌或者是授權的ClientID列表 ,後端架構提供了一個 有效用戶的參數。如果傳入的請求不具有 有效的驗證令牌,或者如果客戶端不上的ClientID白名單, 框架會將用戶爲空

所以,你必須manully趕的情況下,在一個空用戶由基礎設施提供。所以要回答上述問題:請求無效。代碼中的錯誤是CodeFlow對象是爲實際請求重新創建的,但由於沒有設置CredentialStore,令牌丟失,無法重新發送。