使用 cURL 调用 Firebase Cloud Messaging 时“请求的身份验证凭据无效”

Jim*_*nts 2 android curl firebase firebase-cloud-messaging

我正在尝试触发我的 Android 应用程序来接收简单的推送消息。我想用cURL. 我尝试遵循文档 ,但收到 401...这曾经有效,有什么变化吗?

  • 我的服务器密钥:AAAArxt...CelsCl
  • 我的 firebase 项目 URL:my-project...485(取自“常规”下的 URL 或“项目 ID”)
  • 我的设备令牌:fNBu...eHCAgI

在此输入图像描述

我使用以下代码检索了我的设备令牌:

FirebaseMessaging.getInstance().token.addOnSuccessListener { token: String ->
    if (!TextUtils.isEmpty(token)) {
        Log.d("TAG", "retrieve token successful : $token")
    } else {
        Log.w("TAG", "token should not be null...")
    }
}.addOnFailureListener { e: Exception? -> }.addOnCanceledListener {}
.addOnCompleteListener { task: Task<String> ->
    Log.v("TAG", "This is the token : " + task.result)
}
Run Code Online (Sandbox Code Playgroud)

我的卷曲代码:

curl -X POST -H "Authorization: Bearer AAAArxt...CelsCl" -H "Content-Type: application/json" -d '{
"message":{
   "notification":{
     "title":"FCM Message",
     "body":"This is an FCM Message"
   },
   "token":"fNBu...eHCAgI"
}}' https://fcm.googleapis.com/v1/projects/my-project...485/messages:send
Run Code Online (Sandbox Code Playgroud)

回复:

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

创建 OAuth 2.0 令牌,复制access_token以下开头ya29.

在此输入图像描述

返回 403 错误。它指的是project-752077406211。这对我来说是未知的。我没有看到创建/添加现有项目的选项?

{
  "error": {
    "code": 403,
    "message": "Permission 'cloudmessaging.messages.create' denied on resource '//cloudresourcemanager.googleapis.com/projects/project-7520...211' (or it may not exist).",
    "status": "PERMISSION_DENIED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "IAM_PERMISSION_DENIED",
        "domain": "cloudresourcemanager.googleapis.com",
        "metadata": {
          "resource": "projects/project-7520...211",
          "permission": "cloudmessaging.messages.create"
        }
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

loo*_*p88 7

如果您使用 FCM HTTP v1 API,请求中的授权承载应该是 OAuth 2.0 访问令牌,而不是服务器密钥。

以下是您可以尝试生成 OAuth 2.0 访问令牌的选项:

A) 使用Google Developers OAuth 2.0 Playground

  1. 选择并授权 Firebase Cloud Messaging API v1
  2. 选择https://www.googleapis.com/auth/firebase.messaging作为范围
  3. 单击授权 API
  4. 生成授权码后,将其兑换为访问令牌
  5. 复制访问令牌并在请求中使用它

B) 使用Firebase Cloud Messaging Node.js 快速入门项目

  1. 安装 Firebase 管理 SDK 和 Node.js
  2. 下载快速入门项目并按照 README.md 文件中的指南进行操作
  3. 更新index.js并记录访问令牌
  4. 复制访问令牌并在请求中使用它

请注意,访问令牌的常见前缀是ya29.

Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

最后,您可能还想访问此从 FCM Legacy HTTP API 到 FCM HTTP v1 API的迁移指南