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

186
Visualizações
can i use firebase to authorize with my separate server?

I am building a production ready e-commerce website where any local vendor can upload their products and sell directly to customers.

I am using firebase to authenticate with Gmail and phone numbers. My front-end can check if the user is authenticated or not. How can I check on backend if the user is authenticated or not?

Let's say some routes are protected on the client side and only authenticated users can access them. What if someone uses say(postman) and use those routes? Is there anyway i can attach my jwt token and the client will only get it if he authenticates with his gmail or phone?


const signIn = () => {
  return signInWithPopup(auth, provider)
    .then((result) => {
      // This gives you a Google Access Token. You can use it to access the Google API.
      const credential = GoogleAuthProvider.credentialFromResult(result);
      const token = credential.accessToken;
      console.log(token);
      // The signed-in user info.
      const user = result.user;

      console.log("credential:", credential, "token:", token, "user:", user);
    })
    .catch((error) => {
      // Handle Errors here.
      const errorCode = error.code;
      const errorMessage = error.message;
      // The email of the user's account used.
      const email = error.email;
      // The AuthCredential type that was used.
      const credential = GoogleAuthProvider.credentialFromError(error);
      console.log(errorCode, errorMessage, credential, email);
      // ...
    });
};

This authenticates if the user with gmail. How can I use this to tell my backend that this guy is authenticated, and here is his unique id and other info?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Express allow you to use middlewares. Middlewares are pretty simple: some logic that will be executed during the fulfilling of a request, and you can configure when to execute that logic and on what to execute it.

An authorization middleware will give you the exact functionality you're looking for. I'll give you an example:

async function firebaseIdTokenValidationMiddleware(req, res, next) {
  //First, I'll check if the request has the Authorization header and if it contains a Bearer type token
  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith('Bearer ')
  ) {
    //If the reuqest has a token, I'll read it
    const idToken = req.headers.authorization.split('Bearer ')[1];
    if (idToken) {
      try {
        //And I'll use Firebase Auth API to validate the token
        const decodedIdToken = await auth().verifyIdToken(idToken);
        if (decodedIdToken) {
          //If Firebase validates the token, the middleware can allow the next step
          req.authEntity = decodedIdToken;
          return next();
        }
      } 
      //Otherwise, we answer with a "Forbidden" status code
      return res.status(403).json({});
    }
  }

  //If there is no authorization header, we answer with a "Unauthorized" status code
  return res.status(401).json({});
}

Obviously, you can personalize the error codes. The magic is all delegated to Firebase Auth API:

auth().verifyIdToken(MY_TOKEN)

This call verifies if the given token was issued by Firebase Auth itself and if it is a valid one (for example, it verifies if the token is expired or not). After this check, in my example I save the decoded entity in the request:

req.authEntity = decodedIdToken;

It is very helpful if you need to access to those informations in your endpoint's router. You can visit this page for the complete reference of what the Firebase API gives you after the validation.

Note that auth().verifyIdToken() is in the Admin API, so you need to import it in your project.

All we did until now is just creating the middleware. You'll still have to tell Express to use it. You can do it in two ways.

Specifying it on the single router:

app.get('/', firebaseIdTokenValidationMiddleware, async(req,res) => {
  //YOUR LOGIC
}

Globally, and it's called application-level middleware:

app.use(firebaseIdTokenValidationMiddleware);
about 4 years ago · Juan Pablo Isaza 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