GCP Pub/Sub 身份验证令牌未出现在请求中

GCP Pub/Sub authentication token not appearing in the request

我正在设置云 pub/sub 服务以通过 developer documentation 在我的后端接收推送订阅消息。

由于某些原因,发送到我的后端的推送订阅请求从未包含 "token" 查询参数,因此我的后端无法验证推送请求是否来自我的应用程序。开发者文档中的以下代码用于实现验证目的:

  // Verify that the request originates from the application.
  if (req.getParameter("token").compareTo(pubsubVerificationToken) != 0) 
  {
      resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      return;
  }

根据文档,我已经验证 "Service Account Token Creator" 权限被授予 pub/sub 的签名服务,以及启用 "push endpoint authentication" 选项并分配了一个唯一的字符串到 pub/sub 中我的推送订阅中的 "Audience(optional)" 字段。

我想知道我是否还遗漏了什么,或者我弄错了令牌观众的工作方式?为什么 "token" 值没有出现在我的后端收到的请求中?如有任何意见,我们将不胜感激!

正如 John Hanley 所说,令牌在 header 中。但是,当我看你的代码时,我不知道你想要什么"compare"。提供的令牌经常变化(因为它的寿命很短),你不能将它与参考令牌进行比较

但是,您可以从令牌中提取索赔信息,然后对其进行验证。这是我用来提取电子邮件的 Python 代码片段。

    authorization = request.headers['Authorization'][7:]
    b64_profile = authorization.split('.')[1]
    profile = base64.b64decode(b64_profile + '=' * (-len(b64_profile) % 4))
    print(json.loads(profile)['email'])

code snippet quoted here is meant to verify the application token. This token is defined by the application developer as an environmental variable in appengine-web.xml (line 7).

正确验证推送请求来源的令牌是不同的。它由 Cloud Pub/Sub 生成,并以 JWT 的形式出现在推送请求的授权 header 中。这段代码显示了如何验证 JWT(您也可以查看 full sample):

      // Verify and decode the JWT.
      GoogleIdToken idToken = verifier.verify(authorization);

希望这有助于消除困惑。 :-)