Using Google Cloud Endpoints

APIs need protecting — when we were recently using Google App Engine we explored Google Cloud Endpoints and utilised them to improve the security.

Alistair Sykes

--

Cloud Endpoints

Cloud Endpoints allows you to protect and monitor your APIs on any Google Cloud backend through a formalised interface. It provides an API console, hosting, logging, monitoring and other features to help you create, share, maintain, and secure your APIs. https://cloud.google.com/endpoints/

Getting started

To set up endpoints you will need a class which represents your API and change a few config files.

Here is a very simple API which takes the message string from the url query parameter and returns it back via the Message class:

To call this API you would do a GET request to:

https://project-id.appspot.com/_ah/api/echoApi/v1/echo?message=mytestmessage

This is a sample project which can be really helpful in understanding endpoints. Here you can also see the required changes to the config files (appengine-web.xml, web.xml):

https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/app...

To deploy your endpoints code:

./gradlew build
./gradlew endpointsOpenApiDocs
gcloud endpoints services deploy build/endpointsOpenApiDocs/openapi.json

Structure

It is worth thinking about how you want your urls structured (RESTful or otherwise). And throwing an appropriate exception can go a long way (https://cloud.google.com/endpoints/docs/frameworks/java/exceptions).

Enqueuing

In our case, we wanted to start one of our enqueuing task HttpServlets and then have firebase cloud functions call the endpoint.

We used our existing Firebase Cloud Functions to call this new endpoint whenever we detect a change to a file in the Firebase Cloud Storage (for background see here).

Key to the kingdom

Now to secure these urls. Endpoints gives you a few different options here (https://cloud.google.com/endpoints/docs/frameworks/authentication-method), for our use case, we decided to use API Keys. To achieve this we simply add a configuration option to API class:

And then we add an API key through the cloud console (https://console.cloud.google.com/apis/credentials) and add that into our url call in cloud functions:

let url = "https://project-id.appspot.com/_ah/api/update/v1/startEnqueue?key=[API-KEY]";

Halt!

All that’s left to do is to stop the enqueuing and task servlets being accessible directly. That is just the small addition of a security-constraint to the web.xml:

Full Story

Writing an API — a mobile developer’s story

Previous Post

Queued tasks on App Engine for Firebase

Originally published at www.brightec.co.uk.

--

--