2017-09-02 69 views
1

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

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

回答

1

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意味着它应该工作。

+0

感谢@David的有用链接。我缺少的行是:最终的AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes); conn.addRequestProperty(“Content-Type”,“application/json”); conn.addRequestProperty(“Authorization”,“Bearer”+ accessToken.getAccessToken()); – pldenc44