Question

I'm using Google play services on Android to get access to Google Apis and Google cloud Endpoints. I would also be able to get access to the appengine User api using a token from Google Play Services. Is this possible? There is some sample code at this link for OAuth, but is a little vague. Can I pass the oauth token in a header and get a user with the code below??

    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.
        // ...
    }
Was it helpful?

Solution

You can, but this approach isn't going to be as secure as a scenario where you are:

  • using a service-specific scope for a Google API
  • accessing an Endpoints API directly

You can use Google Play Services to obtain a token for the scope you'd like to use. Since you're interested in using the Users API on App Engine, you'll want the userinfo.email scope:

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

Send this to App Engine via the Authorization header:

Authorization: Bearer your_token

Then, using the OAuth API, you can obtain a User object:

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.
  // ...
}

But, in general you don't want to do this! If you protect your application this way, another user can write an application that asks you permission to your userinfo.email scope. Once granted, all they need to do is take the token and pass it to your application, and they appear as you do. Endpoints and other Google APIs have additional logic in place to prevent this kind of behavior, which is why you're better off using one of those approaches.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top