google-cloud-recommendation 有时 returns UNAUTHENTICATED 错误

google-cloud-recommendation Sometime returns UNAUTHENTICATED error

我在我的网络应用程序中使用 userEvents.write 方法。 我发送了一个 JSON 请求,如下所示,授权 header 来自 gcloud auth application-default print-access-token 命令。

{
  "eventType": "detail-page-view",
  "visitorId": "xxxxxxxxxx.xxxxxxxxxxxx",
  "eventTime": "2021-03-06T09:13:58+09:00",
  "experimentIds": [
    "Gie-xxxxxxxxxxxxxxxxxxxxxxxx"
  ],
  "userInfo": {
    "userId": "",
    "ipAddress": "xxx.xxx.xxx.xxx",
    "userAgent": "Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.181 Mobile Safari/537.36",
    "directUserRequest": false
  },
  "uri": "https://xxxxx.net/aaaaaa/item/196160",
  "referrerUri": "https://xxxxxxxx.net/item/196160",
  "productDetails": [
    {
      "product": {
        "id": "196160"
      }
    }
  ]
}

请求url是这样的。 https://retail.googleapis.com/v2/projects/{PROJECT_NUMBER}/locations/global/catalogs/default_catalog/userEvents:write

大多数情况下一切顺利。但是,有时 returns 以下错误。

 {
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.googl
e.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

此错误在应用程序重启后不再出现,并在几天后再次出现。 为什么会出现这个错误?我该如何解决?

我认为当您 运行 应用程序时,用于身份验证方法的 Application Default Credentials 没有获得正确的凭据。

可能是为什么不起作用的原因是因为访问令牌的生命周期有限。正如您所说,错误会在一段时间后出现,最可能的解释是您的令牌已过期,您需要 refresh 它。

If your application needs access to a Google API beyond the lifetime of a single access token, it can obtain a refresh token. A refresh token allows your application to obtain new access tokens.

检查 official documentation 以获取 OAuth 2.0 访问令牌以及如何针对不同语言配置它。