【问题标题】:Authenticate a Google PubSub POST request using OAuth2使用 OAuth2 验证 Google PubSub POST 请求
【发布时间】:2017-09-02 10:50:05
【问题描述】:

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

此链接显示了我在做什么,但它掩盖了身份验证部分。 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 : UNAUTHENTICATED”。如何进行身份验证?

【问题讨论】:

    标签: google-app-engine google-oauth google-cloud-pubsub


    【解决方案1】:

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

    如果您切换到 Java 8 环境,您还可以使用 GAE Std 上的 pubsub 客户端库。 This doc 暗示它应该可以工作。

    【讨论】:

    • 感谢@David 提供有用的链接。我缺少的行是: final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();最终 AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes); conn.addRequestProperty("Content-Type", "application/json"); conn.addRequestProperty("授权", "承载" + accessToken.getAccessToken());
    猜你喜欢
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2018-03-23
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多