Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

549
Visualizações
Use Firebase for Auth and MongoDB for DB

I'am building a react native mobile app with user authentication. I decided to use Firebase auth as it is relatively easy to implement.

I want to use my own backend (node, express) and my own DB (MongoDB) and I need to protect my API calls to check if the user is authenticated and if he has the permission to do the operation.

But I am not at ease with Token validation and I'am not sure I'am doing it the right way...

This is how I am trying to do to make a simple GET or POST request from the client (mobile app):

On the client I retrieve the current User token and send it in the header of my GET request:

firebase.auth().currentUser.getIdToken(true).then(token => {
      fetch('http://localhost:3000', {
        method: 'GET',
        mode: 'cors',
        headers: {
          'AuthToken': token
        }
      }).then(res => res.json().then(res => console.log(res)))
        .catch(err => console.log(err))

An on the server I use a middleware to check the token thanks to firebase admin

function checkAuth(req, res, next) {
  if (req.headers.authtoken) {
    admin.auth().verifyIdToken(req.headers.authtoken)
      .then((token) => {
        console.log(token)
        next()
      }).catch(() => {
        res.status(403).send('Unauthorized')
      });
  } else {
    res.status(403).send('Unauthorized')
  }
}

So for a simple get request from a logged user I have to do the following :

  1. get the user IdToken on client side
  2. send it to the server
  3. check it with firebase
  4. do the operation on my DB
  5. send the data back to the client

Am I doing it the right way ? I don't know if I should store the IdToken on the phone memory in order to avoid geting it from firebase everytime (but the token expires after 1 hour...)

It seems like a lot of "check from firebase" operation just for simple fetch...

Can you give me some advise on how to make all of this more efficient ?

Thanks a lot !

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Overall, your flow looks fine to me, but there are a few things I'd optimize.


By passing true into getIdToken(true), you are forcing it to refresh the token each time before executing your fetch.

There is no need for that, as Firebase already automatically refreshes the ID token in the background. So you can make it less resource intensive, and quite a bit faster, with:

firebase.auth().currentUser.getIdToken().then(token => {
  fetch('http://localhost:3000', {
    ...

After you call admin.auth().verifyIdToken(req.headers.authtoken), you get a result that also shows how long the token is valid for. So you could cache the verified token somewhere until it's close to that time, and use that cached version if you get the same input. That saves you on calls to verifyIdToken`.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda