Adding a Method Protected by OAuth 2.0

We recommend that you use the latest version of this feature, which is renamed to Cloud Endpoints Frameworks for App Engine. This new version supports App Engine standard environment, provides lower latency, and has better integration with App Engine. For more details, see Migrating to 2.0.

In this tutorial, we are adding a new protected method called greetings.authed.

Any client can access your Endpoints API methods unless you protect them with OAuth 2.0. In some scenarios, you may want to restrict access to some or all of the API methods.

To protect a method in the backend API, you need to do the following:

  • Use the allowed_client_ids argument in the @endpoints.api decorator to provide a whitelist of allowed clients.
  • Add the email scope (endpoints.EMAIL_SCOPE) to your @endpoints.api decorator.
  • Add a current user check (endpoints.get_current_user) to each method you wish to protect.

Adding an OAuth 2.0-protected method

The auth configuration is used to define which client IDs can access the API. If you're testing locally with the API explorer you don't need to fill these in, but if you want to try to use your API from a web or mobile client you will need to configure this section with your project-specific values. For more information on creating client IDs, see Creating OAuth 2.0 client IDs.

WEB_CLIENT_ID = 'replace this with your web client application ID'
ANDROID_CLIENT_ID = 'replace this with your Android client ID'
IOS_CLIENT_ID = 'replace this with your iOS client ID'
ANDROID_AUDIENCE = WEB_CLIENT_ID
ALLOWED_CLIENT_IDS = [
    WEB_CLIENT_ID, ANDROID_CLIENT_ID, IOS_CLIENT_ID,
    endpoints.API_EXPLORER_CLIENT_ID]

Because we specify that the endpoints.API_EXPLORER_CLIENT_ID, you can use test this locally without any configuration.

The ANDROID_AUDIENCE is required only for android client and isn't used by any other clients. For more information, see Allowed Client IDs and Audiences

The AuthedGreetingApi service shows how to provide the auth configuration to the @endpoints.api decorator and how to call endpoints.get_current_user:

@endpoints.api(
    name='authed_greeting',
    version='v1',
    # Only allowed configured Client IDs to access this API.
    allowed_client_ids=ALLOWED_CLIENT_IDS,
    # Only allow auth tokens with the given audience to access this API.
    audiences=[ANDROID_AUDIENCE],
    # Require auth tokens to have the following scopes to access this API.
    scopes=[endpoints.EMAIL_SCOPE])
class AuthedGreetingApi(remote.Service):

    @endpoints.method(
        message_types.VoidMessage,
        Greeting,
        path='greet',
        http_method='POST',
        name='greet')
    def greet(self, request):
        user = endpoints.get_current_user()
        user_name = user.email() if user else 'Anonymous'
        return Greeting(message='Hello, {}'.format(user_name))

Notice that we supplied the email scope, endpoints.EMAIL_SCOPE. Although you can add other scopes, you must always include the email scope if you use OAuth.

Deploying and Testing

To test the backend API with real Auth, you must deploy your backend API to the App Engine project you created at the beginning of this tutorial.

To deploy and run:

  1. Deploy the backend you just created to App Engine by running the following command from the directory where your app.yaml is located:

    gcloud app deploy
    

    Optional flags:

    • Include the --project flag to specify an alternate Cloud Platform project ID to what you initialized as the default in the gcloud tool. Example: --project [YOUR_PROJECT_ID]
    • Include the -v flag to specify a version ID, otherwise one is generated for you. Example: -v [YOUR_VERSION_ID]
  2. Check the logs for your project to make sure the backend deployed successfully.

  3. Open API Explorer at this URL in your browser:

    https://your-app-id.appspot.com/_ah/api/explorer
    
  4. In the API Explorer, click authed_greeting API > authed_greeting.greet.

  5. Click Authorize and execute.

  6. When prompted to supply additional scopes, use the default scope provided by clicking Authorize and execute again.

  7. Observe the authorization in the request, and a greeting with your user name in the response.

Code summary

If the request coming in from the client has a valid auth token or is in the list of authorized clientIDs, the backend framework supplies a valid User when endpoints.get_current_user() is invoked. If the incoming request does not have a valid auth token or if the client is not on the clientIDs whitelist, endpoints.get_current_user() returns None.

Accordingly, if the request comes from a client that isn't in the whitelist, there will be no current user. Your own code must handle both the case where the current user is null and the case where there is a valid current user. If there is no user, for example, you could choose to return a not-authenticated error or perform some other desired action. In this tutorial, we simply identify the non authenticated user as Anonymous.

What's next

This completes the tutorial.

For the advanced topics such as using datastore and creating clients of the API backend, see the following:

Send feedback about...

App Engine standard environment for Python