使用 OAuth2 验证 Google PubSub POST 请求

Authenticate a Google PubSub POST request using OAuth2

我需要形成一个 POST 来发布 Google PubSub 消息。我无法使用客户端库,因为它们使用与 Google App Engine 不兼容的 gRPC。我可以形成关键 POST 请求,但我不确定如何使用 OAuth2 对其进行身份验证。

这个 link 显示了我在做什么,但它掩盖了身份验证部分。 https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics/publish

(如果 GAE 标准环境支持 gRPC 就无所谓了。)

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();

此代码返回“401:未经验证”。我如何验证它?

App Engine 有一个 API 来获取您可以在调用 Google 服务时使用的访问令牌。有关文档和示例,请参阅 https://cloud.google.com/appengine/docs/standard/java/appidentity/#asserting_identity_to_google_apis

如果切换到 Java 8 环境,您也许还可以在 GAE Std 上使用 pubsub 客户端库。 This doc 表示它应该有效。