簡體   English   中英

從AccountManager獲取基本的Google身份驗證令牌

[英]Obtaining a basic google auth-token from AccountManager

我想從AccountManager獲取Google身份驗證令牌,然后將其發送到我的Web服務(不在App Engine上托管)以驗證用戶身份(如果不需要此權限,我只需要電子郵件地址,最后是他的名字)。

“ getAuthToken”方法的“ authTokenType”參數必須使用什么?

我必須使用哪個Google Api來獲取用戶電子郵件?

使用OpenID Connect可以做到這一點,但是這是試驗性的,因此將來可能會更改細節。 如果您為“ https://www.googleapis.com/auth/userinfo.email”或“ https://www.googleapis.com/auth/userinfo.profile”范圍獲得OAuth令牌,則可以使用它來獲取來自https://www.googleapis.com/oauth2/v1/userinfo的用戶信息(包括電子郵件)。 當然,用戶需要對此進行授權。

從理論上講,您應該可以使用“ oauth2:https://www.googleapis.com/auth/userinfo.profile”作為令牌類型從AcccountManager獲取令牌,但是在我的設備上似乎無法正常運行(Galaxy連結股票4.0.4)。 由於無法通過AccountManager獲取令牌(至少到目前為止),唯一可靠的方法是使用WebView並通過瀏覽器獲取令牌,如下所述: https : //developers.google.com/accounts/docs / MobileApps

這里有一個演示Web應用程序可以執行此操作: https : //oauthssodemo.appspot.com

(最新)更新:Google Play服務已經發布,這是獲取OAuth令牌的首選方式。 它應在所有裝有Android 2.2及更高版本的設備上可用。 獲取配置文件令牌確實可以使用它,實際上他們在演示應用程序中使用了它

我也遇到了問題,因為找不到類似參考的東西。 也許這可以為您提供幫助(從使用帳戶管理器的Android示例中復制的代碼):

  1. 在您的Android應用程序的事件處理程序中的某處,發出請求auth令牌的請求,以獲取Android中用戶的電子郵件地址:

     _accountMgr = AccountManager.get(this); Account [] accounts = _accountMgr.getAccounts(); Account account = accounts[0]; // For me this is Google, still need to figure out how to get it by name. _accountMgr.getAuthToken(account, AUTH_TOKEN_TYPE, false, new GetAuthTokenCallback(), null); 
  2. 在回調中,提取訪問令牌:

     private class GetAuthTokenCallback implements AccountManagerCallback<Bundle> { public void run(AccountManagerFuture<Bundle> result) { Bundle bundle; try { bundle = result.getResult(); final String access_token = bundle.getString(AccountManager.KEY_AUTHTOKEN); // store token somewhere you can supply it to your web server. } catch (Exception e) { // do something here. } } } 
  3. 向您的Web服務器提出一些請求,並提供訪問令牌。

  4. 在Web服務器上,驗證訪問令牌並獲取電子郵件地址:

     curl -d 'access_token=<this is the token the app sent you>' https://www.googleapis.com/oauth2/v1/tokeninfo 

    您應該得到這樣的內容:

     { "issued_to": "<something>.apps.googleusercontent.com", "audience": "<something>.apps.googleusercontent.com", "scope": "https://www.googleapis.com/auth/userinfo.email", "expires_in": 3562, "email": "<users email address>", "verified_email": true, "access_type": "online" } 

    或出現問題:

     { "error": "invalid_token", "error_description": "Bad Request" } 

您可以使用Google+ People API獲取用戶的姓名。 (它將不提供用戶的電子郵件地址)。

如果可以,則可以使用“知道您在Google上的身份”作為authTokenType。

Google提供了一個示例應用程序,該應用程序演示了如何將AndroidAccountManager與Google+ API結合使用。

鏈接: http : //code.google.com/p/google-plus-java-starter/source/browse/#hg%2Fandroid

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM