关于Appengine的Oauth与Google Play服务

Pat*_*ick 3 google-app-engine android oauth-2.0 google-cloud-endpoints google-play-services

我在Android上使用Google Play服务来访问Google Apis和Google云端点.我还可以使用Google Play服务中的令牌访问appengine User 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.
        // ...
    }
Run Code Online (Sandbox Code Playgroud)

Dan*_*oet 6

您可以,但这种方法不会像您所处的场景一样安全:

  • 使用特定于服务的Google API范围
  • 直接访问Endpoints API

您可以使用Google Play服务获取您要使用的范围的令牌.由于您对在UsersApp Engine上使用API 感兴趣,因此您需要使用userinfo.email范围:

String mScope = "https://www.googleapis.com/auth/userinfo.email";
try {
    token = GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
} catch {
    ...
}
Run Code Online (Sandbox Code Playgroud)

通过Authorization标头将其发送到App Engine:

Authorization: Bearer your_token
Run Code Online (Sandbox Code Playgroud)

然后,使用OAuthAPI,您可以获取一个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.
  // ...
}
Run Code Online (Sandbox Code Playgroud)

但是,一般来说你不想这样做!如果您以这种方式保护您的应用程序,另一个用户可以编写一个应用程序,要求您对您的userinfo.email范围进行许可.一旦被授予,他们需要做的就是获取令牌并将其传递给您的应用程序,它们就像您一样出现.端点和其他Google API具有额外的逻辑来防止这种行为,这就是为什么你最好使用这些方法之一.