2012-08-10 84 views
2

我在谷歌應用程序項目上工作,我正在努力與java oauth庫(1.10.1-beta)。Oauth:從哪裏獲取AuthorizationCodeFlow的userId。 createAndStoreCredential?

我緊跟:http://code.google.com/p/google-oauth-java-client/wiki/OAuth2#Authorization_code_flow

問題是,我不從那裏我應該得到用戶id或USEREMAIL知道。我知道有userinfo API,但我實際上是在創建憑證,所以我無法訪問userinfo API AFIAK。

我的應用程序在localhost上很好地工作(因爲[email protected]用戶總是在那裏),但在谷歌引擎環境中部署時失敗(NullPointerException user.getUserId())。

// we ask for token because we got authCode 
GoogleTokenResponse gTokenResponse = userUtils.getFlow().newTokenRequest(authCode).setRedirectUri(userUtils.getRedirectUri()).execute(); 

//trying to search for user email/id/whatever 
User user = UserServiceFactory.getUserService().getCurrentUser(); 

//user is null -> nullPointerException is thrown 
userUtils.getFlow().createAndStoreCredential(gTokenResponse, user.getUserId()); 

請您指出我使用案例中的缺陷還是給我一個提示?我在SDK示例,Stackoverflow和這裏搜索了很多,但沒有太多的實現。

PS:在方法AuthorizationCodeFlow.createAndStoreCredential(...)是userId,只有當你使用永久性存儲器作爲憑證時是強制性的,是的,我使用的是這樣userId不能爲null。

謝謝。

回答

0

在識別用戶(身份驗證)之前,您正在進行OAUTH(授權)。您必須將用戶重定向到登錄頁面時未登錄他:

UserServiceFactory.getUserService().getCurrentUser() == null 

你做到這一點的用戶重定向到loginUrl:下一次用戶到達您的應用程序

String loginUrl = userService.createLoginURL(request.getOriginalRef().toString()); 

,他將登錄,並且您可以詢問userId。

+0

但是,如果在用戶授予應用程序訪問權後運行代碼,那麼應用程序必須知道誰登錄了Google帳戶。 – Martin85 2012-08-12 20:36:56

+0

if UserServiceFactory.getUserService()。getCurrentUser()== null 那麼恐怕用戶沒有登錄他的谷歌賬戶 – koma 2012-08-13 07:33:02