从AccountManager获取基本的Google身份验证令牌

时间:2012-05-12 17:05:14

标签: android google-api accountmanager

我想从AccountManager获取一个Google Authtoken,我可以将其发送到我的Web服务(不在App Engine上托管)来验证用户(如果不需要此权限,我只需要电子邮件地址,最后是他的名字) )。

我必须使用“getAuthToken”方法的“authTokenType”参数吗?

我必须使用google Api来获取用户电子邮件吗?

3 个答案:

答案 0 :(得分:4)

这可以使用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 Nexus,库存4.0.4)。由于通过AccountManager获取令牌不起作用(至少目前为止),唯一可靠的方法是使用WebView并通过浏览器获取一个,如下所述:https://developers.google.com/accounts/docs/MobileApps

这里有一个演示网络应用程序:https://oauthssodemo.appspot.com

(已故)更新:Google Play服务已发布,是获取OAuth令牌的首选方式。它应该适用于Android 2.2及更高版本的所有设备。获取配置文件令牌确实可以使用它,实际上它们在演示应用程序中使用它

答案 1 :(得分:2)

我也遇到过这个问题,因为我找不到像引用这样的东西。也许这可以帮助您(使用客户经理从Android示例中复制的代码):

  1. 在Android应用的事件处理程序中的某个位置,发出请求身份验证令牌以获取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. 向您的网络服务器发出一些请求,提供访问令牌。

  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"
    }
    

答案 2 :(得分:0)

您可以使用Google+ People API获取用户名。 (它不会提供用户的电子邮件地址)。

如果可以,您可以使用“了解您在Google上的身份”作为authTokenType。

Google提供了一个示例应用程序,演示了如何将AndroidAccountManager与Google+ API结合使用。

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

相关问题