为VAPID订阅创建FCM令牌时发生未授权错误

时间:2019-04-29 11:14:10

标签: firebase firebase-cloud-messaging vapid

根据文章 https://developers.google.com/instance-id/reference/server#manage_registration_tokens_for_push_subscriptions

在响应中出现以下错误

{
    "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"
    }
}

以下是根据文章使用的代码:

var rp = require('request-promise');
var fs = require('fs');
var google = require('googleapis');
var request = require("request");



var SCOPES = ['https://www.googleapis.com/auth/firebase.messaging'];


function getAccessToken() {
  return new Promise(function(resolve, reject) {
    var key = require('./test-firebase-2-firebase-adminsdk-9n4rb-6a33f8d856.json');
    var jwtClient = new google.auth.JWT(
      key.client_email,
      null,
      key.private_key,
      SCOPES,
      null
    );
    jwtClient.authorize(function(err, tokens) {
      if (err) {
        reject(err);
        return;
      }
      resolve(tokens.access_token);
    });
  });
}

getAccessToken().then(function(accessToken) {
    console.log("AT : "+accessToken);


    bodyObj = {"endpoint":"https://fcm.googleapis.com/fcm/send/eLdk3sJBXwk:APA91bEUbGhrzMrO09NkvAp_zKHP5oUYTKRhdWvkVUBNmLRPb6HHgtNyOfD_WEKqxXzqXBlqJEt1HHD_XE1sN2YecLnehEQPHfXHFX16WxXo4DzxUyEW6LNNaGconHYrNAJ7kPOsNCyt","keys":{"p256dh":"BGhtJDtRDUGUnt3hR5TFIGH35TGsa_XPz7uKG7yos6xWNxngRha1Hz7uHqms6E4XuhsuSqk1tJzhLdfpkmElJaA","auth":"p_Euf4uiM8hOakFPsZIR5g"}};


    var options = {
        method: 'POST',
        url: 'https://iid.googleapis.com/v1/web/iid',
        headers:
        {
            'Authorization' : 'Bearer '+accessToken,
            'Crypto-Key': 'p256ecdsa=<Public Key>',
            'Content-Type': 'application/json'
        },
        body: bodyObj,
        json: true
    };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);
        console.log('Request end');
        console.log(body);
    });
});

  1. 根据说明创建服务凭证文件。
  2. 成功生成了OAuth 2令牌。
  3. 根据文档[https://www.googleapis.com/auth/firebase.messaging]
  4. 通过了正确的范围
  5. 将VAPID令牌发布到https://iid.googleapis.com/v1/web/iid时返回错误。

0 个答案:

没有答案