V
V
Volodymyr Palamar2021-05-27 12:50:36
JavaScript
Volodymyr Palamar, 2021-05-27 12:50:36

How to fix registration error in fcm?

Hello,
somehow I didn’t really want to pull the whole firebase messaging library, so I wanted to try to simply “copy” the requests and adapt them to my needs.

const messaging = firebase.messaging(); // инициализация
let tok = messaging.getToken({vapidKey: "BOykmB-jJz3ZZQZGFPT9zTOvGHz7LO_MwPumyzUz79jyQii8aswGQcUQxKjUdpBqD22QH1q274sH9rr4YiYnNXY"});
// Получение токена

Help Chrome Dev Tools I managed to catch 2 requests
Obtaining a FIS token
fetch("https://firebaseinstallations.googleapis.com/v1/projects/meu-starter/installations", {
  "headers": {
    "accept": "application/json",
    "content-type": "application/json",
    "sec-ch-ua": "\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"",
    "sec-ch-ua-mobile": "?0",
    "x-goog-api-key": "AIzaSyA5Xvv-O_G531RILC50FlRBSWr-HVzlEJA"
  },
  "referrer": "https://fcm-web-push-ionic.web.app/",
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": "{\"fid\":\"fz2TnZNjsnPSBIn-FaNsl7\",\"authVersion\":\"FIS_v2\",\"appId\":\"1:581248963506:web:9f09b416b6fbf3a8ee4aab\",\"sdkVersion\":\"w:0.3.9\"}",
  "method": "POST",
  "mode": "cors",
  "credentials": "omit"
});


Subscription registration
fetch("https://fcmregistrations.googleapis.com/v1/projects/meu-starter/registrations", {
  "headers": {
    "accept": "application/json",
    "content-type": "application/json",
    "sec-ch-ua": "\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"",
    "sec-ch-ua-mobile": "?0",
    "x-goog-api-key": "AIzaSyA5Xvv-O_G531RILC50FlRBSWr-HVzlEJA",
    "x-goog-firebase-installations-auth": "FIS eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBJZCI6IjE6NTgxMjQ4OTYzNTA2OndlYjo5ZjA5YjQxNmI2ZmJmM2E4ZWU0YWFiIiwiZXhwIjoxNjIyNjcxODk5LCJmaWQiOiJmejJUblpOanNuUFNCSW4tRmFOc2w3IiwicHJvamVjdE51bWJlciI6NTgxMjQ4OTYzNTA2fQ.AB2LPV8wRQIhAPzGBi7GwI8Nq4jC1Nmu7NOCdUwEeeUw7s0h1vPGn6mvAiAp3hKYd3oObriDG3Jd8bphG7_HCVezblrsLwERERrpjA"
  },
  "referrer": "https://fcm-web-push-ionic.web.app/",
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": "{\"web\":{\"endpoint\":\"https://fcm.googleapis.com/fcm/send/dc8UhGIxyxE:APA91bGa-9T_Z_ftXTsSlPdGTvMWAf_yTbE1dCfhmukKQXnl4ARUciwYxHIHBYCQQFcF9Lm8_TVbP_LTdndh5L8GdxRbcr0JglQl-d8RD4NSyhAYHtENfcmQdB_lz7pA6j1iZf6vrIRI\",\"p256dh\":\"BLzINEhrcLDyEAbbumvXjixrVy3_sa0L2FShus0_CB0ZuxH2vtKqi5OHbEFIuY-HN02FHUzJ8MCPdpabG3O43tI\",\"auth\":\"09oJ8lO8q_P8v7x4ctL4gg\"}}",
  "method": "POST",
  "mode": "cors",
  "credentials": "omit"
});

Of all the data transmitted in requests, the script generates only FID, but since there is a .map file, I managed to get the function
generateFid
function generateFid() {
  const VALID_FID_PATTERN = /^[cdef][\w-]{21}$/;
  const INVALID_FID = '';
  function bufferToBase64UrlSafe(array) {
  const b64 = btoa(String.fromCharCode(...array));
  return b64.replace(/\+/g, '-').replace(/\//g, '_');
  }
  function encode(fidByteArray){
  const b64String = bufferToBase64UrlSafe(fidByteArray);
  return b64String.substr(0, 22);
}
  try {
    // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5
    // bytes. our implementation generates a 17 byte array instead.
    const fidByteArray = new Uint8Array(17);
    crypto.getRandomValues(fidByteArray);

    // Replace the first 4 random bits with the constant FID header of 0b0111.
    fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);

    const fid = encode(fidByteArray);

    return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;
  } catch {
    // FID generation errored
    return INVALID_FID;
  }
}

My implementation of the functions (these are test functions to check if they work)
installation
function instalation(config){
  return fetch("https://firebaseinstallations.googleapis.com/v1/projects/"+config.projectId+"/installations", {
  "headers": {
    Accept:"application/json",
    "content-type": "application/json",
    "x-goog-api-key": config.apiKey
  },
  "body": JSON.stringify({
    fid:config.fid,
    authVersion:"FIS_v2",
    appId:config.appId,
    sdkVersion:"w:0.3.9"
  }),
  "method": "POST",
}).then(r=>r.json()).then(r=>(firebaseConfig.auth=r.authToken.token,r));
}

registration
function registration(config,subscribe){
  return fetch("https://fcmregistrations.googleapis.com/v1/projects/"+config.projectId+"/registrations", {
  "headers": {
                       "Content-Type": "application/json",
                       Accept: "application/json",
                       "x-goog-api-key": config.apiKey,
                       "x-goog-firebase-installations-auth": "FIS " + config.auth
                    },
  "body": JSON.stringify({
    web:{
      auth:subscribe.keys.auth,
      endpoint:subscribe.endpoint,
      p256dh:subscribe.keys.p256dh
    }
  }),
  "method": "POST",
});
}

The launch of this miracle is carried out from the console because this is a test code
let firebaseConfig = {
    apiKey: "AIzaSyDj0wCbpDZhMltjfUQyaa1RcVQ4St0Cr0o",
    authDomain: "rent-a-car-push.firebaseapp.com",
    projectId: "rent-a-car-push",
    storageBucket: "rent-a-car-push.appspot.com",
    messagingSenderId: "438059317038",
    appId: "1:438059317038:web:f6eb07747d04fe07a7acbf",
    fid:generateFid()
  };
let subscribeOptions = {
      userVisibleOnly: true,
      applicationServerKey: 
        'BBAMlBDE6qiir8vEXPyYPwHhVt7zZ40HeyT0v1AIUeC4l1j7xXfTNYQthsf36_W0setCp6-683jptFBSTId7mps'
    };
navigator.serviceWorker.ready.then(async registration => {
registration.pushManager.subscribe(subscribeOptions).then(ps=>firebaseConfig.push=ps)
})
//Concole
inst = instalation(firebaseConfig)

reg = registration(firebaseConfig,firebaseConfig.push.toJSON())
installation(firebaseConfig)
{
  "name": "projects/438059317038/installations/eLQUPYLFRkCx6-OejBEc7o",
  "fid": "eLQUPYLFRkCx6-OejBEc7o",
  "refreshToken": "2_bqxVZoUwi4oLD1FI2GAhttk3OTwzf94jU-RupmoIdoB3ZrJH5UbyY80HtMN7F4Ck",
  "authToken": {
    "token": "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBJZCI6IjE6NDM4MDU5MzE3MDM4OndlYjpmNmViMDc3NDdkMDRmZTA3YTdhY2JmIiwiZXhwIjoxNjIyNzEzMTkxLCJmaWQiOiJlTFFVUFlMRlJrQ3g2LU9lakJFYzdvIiwicHJvamVjdE51bWJlciI6NDM4MDU5MzE3MDM4fQ.AB2LPV8wRQIgcwoj-pG0NDLol1qAyTedUL8OGjdo5ok4c4ZM6K9ywgACIQDxvWcAPG9Xq8nMyXHpYbMAUP_k3-ESNgtkYYl9wT_wbA",
    "expiresIn": "604800s"
  }
}

The first function works like clockwork
, but the second returns an error
{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. 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"
  }
}

I checked all the fields for correspondence, I pass the correct data, but still the authorization error. Who knows how to solve?
Send request

instalation
fetch("https://firebaseinstallations.googleapis.com/v1/projects/rent-a-car-push/installations", {
  "headers": {
    "accept": "application/json",
    "accept-language": "uk-UA,uk;q=0.9,en-US;q=0.8,en;q=0.7",
    "content-type": "application/json",
    "sec-ch-ua": "\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"",
    "sec-ch-ua-mobile": "?0",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "cross-site",
    "x-client-data": "CK61yQEIlrbJAQiltskBCMS2yQEIqZ3KAQj+z8oBCKidywEIoKDLAQi/oMsBCN3yywEIp/PLAQ==",
    "x-goog-api-key": "AIzaSyDj0wCbpDZhMltjfUQyaa1RcVQ4St0Cr0o"
  },
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": "{\"fid\":\"eLQUPYLFRkCx6-OejBEc7o\",\"authVersion\":\"FIS_v2\",\"appId\":\"1:438059317038:web:f6eb07747d04fe07a7acbf\",\"sdkVersion\":\"w:0.3.9\"}",
  "method": "POST",
  "mode": "cors",
  "credentials": "omit"
});

registration
fetch("https://fcmregistrations.googleapis.com/v1/projects/rent-a-car-push/registrations", {
  "headers": {
    "accept": "application/json",
    "accept-language": "uk-UA,uk;q=0.9,en-US;q=0.8,en;q=0.7",
    "content-type": "application/json",
    "sec-ch-ua": "\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"",
    "sec-ch-ua-mobile": "?0",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "cross-site",
    "x-client-data": "CK61yQEIlrbJAQiltskBCMS2yQEIqZ3KAQj+z8oBCKidywEIoKDLAQi/oMsBCN3yywEIp/PLAQ==",
    "x-goog-api-key": "AIzaSyDj0wCbpDZhMltjfUQyaa1RcVQ4St0Cr0o",
    "x-goog-firebase-installations-auth": "FIS eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBJZCI6IjE6NDM4MDU5MzE3MDM4OndlYjpmNmViMDc3NDdkMDRmZTA3YTdhY2JmIiwiZXhwIjoxNjIyNzEzMTkxLCJmaWQiOiJlTFFVUFlMRlJrQ3g2LU9lakJFYzdvIiwicHJvamVjdE51bWJlciI6NDM4MDU5MzE3MDM4fQ.AB2LPV8wRQIgcwoj-pG0NDLol1qAyTedUL8OGjdo5ok4c4ZM6K9ywgACIQDxvWcAPG9Xq8nMyXHpYbMAUP_k3-ESNgtkYYl9wT_wbA"
  },
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": "{\"web\":{\"auth\":\"ywghIQa8tEvuD_i6vF2vmg\",\"endpoint\":\"https://fcm.googleapis.com/fcm/send/fv-i0_aiDuQ:APA91bFS6tlnD6_jK7zW8TZFsuBh4mdzTr-Saejb0ljtntDZtGhOZjQrseXLA4-S1tgFt-pNOLuMc4TRAbJStFR-weHvfZG08useIXhhEryoRD80s9k_g8TaUGLjOVmayanF436DhcnI\",\"p256dh\":\"BLNyyYMfaJFSqXfDH_-L9witFUL-Fj3aweN2nJYhBMaqAvK7roakSeNCRlW9c4_yhL-284qgbWQZMup0uOcxACM\"}}",
  "method": "POST",
  "mode": "cors",
  "credentials": "omit"
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Volodymyr Palamar, 2021-05-27
@GORNOSTAY25

Need to pass applicationPubKey during registration

"body": JSON.stringify({
    web:{
      "applicationPubKey":"BBAMlBDE6qiir8vEXPyYPwHhVt7zZ40HeyT0v1AIUeC4l1j7xXfTNYQthsf36_W0setCp6-683jptFBSTId7mps",
      auth:subscribe.keys.auth,
      endpoint:subscribe.endpoint,
      p256dh:subscribe.keys.p256dh
    }
  }),

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question