Search code examples
google-app-enginegoogle-oauthgoogle-cloud-pubsub

Authenticate a Google PubSub POST request using OAuth2


I need to form a POST to publish a Google PubSub message. I can't use the client libraries because they use gRPC which is incompatible with Google App Engine. I can form the critical POST request, but I'm not sure how to authenticate it using OAuth2.

This link shows what I'm doing, but it obscures the authentication part. https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics/publish

(If GAE standard environment would support gRPC this would not matter.)

JSONObject obj = new JSONObject();
JSONArray attr = new JSONArray();
obj.put("script_name","foo_script.py");
obj.put("script_args","arg1");
attr.put(obj);
JSONObject jsontop = new JSONObject();
jsontop.put("messages",attr);
URL url = new URL("https://pubsub.googleapis.com/v1/projects/{my-URL}/topics/topic_run_script:publish");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

This code comes back "401 : UNAUTHENTICATED". How do I authenticate it?


Solution

  • App Engine has an API to fetch an access token that you can use to when calling Google services. For documentation and an example, see https://cloud.google.com/appengine/docs/standard/java/appidentity/#asserting_identity_to_google_apis

    You might also be able to use the pubsub client library on GAE Std if you switch to the Java 8 environment. This doc implies that it should work.