Szymon Brud
Szymon Brud

Reputation: 127

How is correctly way to send firebase auth tokenId between front-end and node.js backend

I am during create a chat-app. I want to find a good way to safely connect front and backend using a TokenId from firebase auth.

  1. Do I have to in every request from my front to backend send a TokenId?
  2. It is possible to do it in session or something like that I can send token once and verified it once time too?

My current road.enter image description here

My code front end where I send a token:

fetch('http://localhost:5500/check', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ token: token }),
  })
    .then(data => data.json())
    .then(e => console.log(e))
    .catch(err => console.log(err));
});

I get token on front end like that:

firebase.auth().currentUser.getIdToken(true)

My code backend verify token:

router.post('/check', urlencodedParser, (req, res) => {
  const {token} = req.body;

  admin
    .auth()
    .verifyIdToken(token)
    .then(function (decodedToken) {
      // let uid = decodedToken.uid;
      res.setHeader('Content-Type', 'application/json');
      res.send({status: 'Ok'});
    })
    .catch(function (error) {
      console.log(error);
      res.setHeader('Content-Type', 'application/json');
      res.send({status: 'err'});
    });
});

Upvotes: 2

Views: 1258

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598807

  1. Do I have to in every request from my front to backend send a TokenId?

That is what the Firebase clients and back-end services do: they send (and reverify) the ID token with every request. The server caches is the public key that is needed to decode the token, but aside from that are pretty much stateless with regards to the user/ID token.

  1. It is possible to do it in session or something like that I can send token once and verified it once time too?

You can definitely keep the token in a session, but that means that you'll need to send the session ID instead of the token itself, and have to implement state management for your sessions.

Upvotes: 1

Related Questions