2015-05-28 52 views
0

在我的桌面應用程序中,我已成功獲取OAuth2 access_token。安裝應用程序的OAuth 2.0 - 如何調用我的AppEngine應用程序

我可以通過向HTTP請求頭成功地調用谷歌的API:

Authorization: Bearer ya29.gQHsr_vr9P6nsEi06OKWkqKlvzD... 

現在我想獲得從http請求當前用戶 - 我該怎麼做呢?我不想實施Google Cloud Endpoints。

@Override 
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { 
{ 
    // How do I get the logged in user ? 
    com.google.appengine.api.users.User googleUser = ?; 
    return user; 
} 

回答

0

如果我正確理解你的問題。

可以得到證書後,請執行下列操作:

/** 
    * Send a request to the UserInfo API to retrieve the user's information. 
    * 
    * @param credentials OAuth 2.0 credentials to authorize the request. 
    * @return User's information. 
    * @throws NoUserIdException An error occurred. 
    */ 
    static Userinfoplus getUserInfo(Credential credentials) 
     throws NoUserIdException { 
    Oauth2 userInfoService = new Oauth2.Builder(
     HTTP_TRANSPORT, JSON_FACTORY, credentials) 
     .setApplicationName(APPLICATION_NAME) 
     .build(); 
    Userinfoplus userInfo = null; 
    try { 
     userInfo = userInfoService.userinfo().get().execute(); 
    } catch (IOException e) { 
     System.err.println("An error occurred: " + e); 
    } 
    if (userInfo != null && userInfo.getId() != null) { 
     return userInfo; 
    } else { 
     throw new NoUserIdException(); 
    } 

來源: https://developers.google.com/drive/web/credentials

讓我知道這是否可以幫助你。

0

我認爲你需要的是已經解釋here。從該鏈接的「OAuth服務提供商和App引擎」部分中稍微修改的片段:

import com.google.appengine.api.users.User; 
import com.google.appengine.api.oauth.OAuthRequestException; 
import com.google.appengine.api.oauth.OAuthService; 
import com.google.appengine.api.oauth.OAuthServiceFactory; 
import com.google.appengine.api.oauth.OAuthServiceFailureException; 

// ... 
@Override 
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { 
    // ... 
    User user = null; 
    try { 
    OAuthService oauth = OAuthServiceFactory.getOAuthService(); 
    user = oauth.getCurrentUser(); 

    } catch (OAuthRequestException e) { 
    // The consumer made an invalid OAuth request, used an access token that was 
    // revoked, or did not provide OAuth information. 
    // ... 
    } 

    // Rest of your handler code 
} 
+0

謝謝。我測試了這種方法 - 但沒有奏效。我想從桌面應用程序調用我的api。獲取已安裝應用的OAuth2的access_token與您提供的鏈接不同。 [使用OAuth 2.0安裝應用程序](https://developers.google.com/identity/protocols/OAuth2InstalledApp) –

+0

我明白了;但您分享的鏈接解釋瞭如何從客戶端應用程序獲取access_token。另一方面,我的答案與服務器端有關,即您在App Engine上部署的內容。如果您正確地處理與應用程序服務器通信的桌面應用程序的請求,即設法獲取有效的access_token,並將此令牌嵌入到頭文件的「授權」字段中(如您所解釋的),那麼它應該工作。你正在經歷什麼樣的錯誤,服務器端? – asamarin

相關問題