Appengine上使用Google Play服务的Oauth

3
我在Android上使用Google Play服务来访问Google API和Google Cloud Endpoints。我也可以使用来自Google Play服务的令牌来访问appengine用户API。这可能吗?在此链接中有一些OAuth示例代码,但是有点含糊不清。我能否将OAuth令牌传递到标头中并使用下面的代码获取用户?
    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.
        // ...
    }
1个回答

6
你可以这样做,但这种方法不如以下两种方案安全:
  • 使用 Google API 的服务特定范围
  • 直接访问 Endpoints API
你可以使用 Google Play 服务来获取想要使用的范围的令牌。由于你有兴趣在 App Engine 上使用“用户”API,因此需要使用“userinfo.email”范围。
String mScope = "https://www.googleapis.com/auth/userinfo.email";
try {
    token = GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
} catch {
    ...
}

通过授权头将此内容发送到App Engine:

Authorization: Bearer your_token

然后,使用OAuth API,你可以获取一个User对象:
String mScope = "https://www.googleapis.com/auth/userinfo.email";
User user = null;
try {
  OAuthService oauth = OAuthServiceFactory.getOAuthService();
  user = oauth.getCurrentUser(mScope);
} catch (OAuthRequestException e) {
  // The consumer made an invalid OAuth request, used an access token that was
  // revoked, or did not provide OAuth information.
  // ...
}

但是,总的来说你不应该这样做! 如果您以这种方式保护您的应用程序,另一个用户可以编写一个应用程序,请求您的userinfo.email范围的权限。一旦授予,他们只需要获取令牌并将其传递给您的应用程序,就会出现与您相同的情况。端点和其他Google API已经采取了额外的逻辑来防止这种行为,这就是为什么使用其中一种方法更好。


谢谢您的回复,它帮助我澄清了一些事情。我肯定会使用GS + Endpoints方法。 - Patrick Jackson
嗨@Dan,我在服务器端使用GS + Endpoint和Sprint Oauth2身份验证,但是我收到了“需要完全授权”的错误消息。你有什么想法吗? - kirti Hudda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接