Google Cloud Platform
Java

OAuth API for Java

Python |Java |PHP |Go

The App Engine OAuth API uses the OAuth protocol and provides a way for your app to authenticate users who are requesting access without asking for their credentials (username and password).

  1. OAuth 2.0
    1. Generating an access token
    2. Using the API

OAuth 2.0

OAuth 2.0 access tokens supplied by the Google Sign-In library and low-level OAuth 2.0 endpoints can be used to authenticate clients with the OAuth API and retrieve user identity information.

Generating an access token

Follow the steps outlined at Using OAuth 2.0 to Access Google APIs.

The client should send the resulting OAuth 2.0 access token in the Authorization: Bearer HTTP Request Header on every request to your AppEngine app.

You can also obtain an access token using one of the Google Sign-in client libraries for Android, iOS, or the web.

Using the API

When a client sends a request to your app, the authorization header of the request includes an OAuth access token that has one or more scopes associated with it, indicating what APIs the client can access. Your app can retreive information about the user who granted the access token by running this code:

OAuthService oauth = OAuthServiceFactory.getOAuthService();
String scope = "https://www.googleapis.com/auth/userinfo.email";
Set<String> allowedClients = new HashSet<>();
allowedClients.add("407408718192.apps.googleusercontent.com"); // list your client ids here

try {
  User user = oauth.getCurrentUser(scope);
  String tokenAudience = oauth.getClientId(scope);
  if (!allowedClients.contains(tokenAudience)) {
    throw new OAuthRequestException("audience of token '" + tokenAudience
        + "' is not in allowed list " + allowedClients);
  }
  // proceed with authenticated user
  // ...
} catch (OAuthRequestException ex) {
  // handle auth error
  // ...
} catch (OAuthServiceFailureException ex) {
  // optionally, handle an oauth service failure
  // ...
}

getCurrentUser returns an object representing the user associated with the request. If the access token is invalid, the method returns an error.