skip to Main Content

User is authenticated on client side with firebase sdk.

on server side, there is nodejs with also the sdk installed. This server code is valid as i’m able to use the db:

var firebase = require("firebase/compat/app");
require("firebase/compat/database");
require("firebase/compat/auth");

const firebaseConfig = {
  apiKey: "Axxx4",
  authDomain: "movtxxxom",
  projectId: "moxxx2",
  storageBucket: "movxxom",
  messagingSenderId: "14xx9",
  appId: "1:1xxxea13c",
  measurementId: "GxxFL",
  databaseURL: "httpxxx/",
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

This code is valid.

And here is a (fastify) route where I want to get user information:

fastify.get("/login-success", async (request, reply) => {
 // Return View

 const user = firebase.auth().currentUser;
 console.log(user);
 return reply.view("/templates/login-success.ejs", {
   text: "Log in success",
 });
});

The user variable is always null.

How is the proper way to handle this?

  • Is there a firebase function i’m unaware of that could retrieve current user info ?
  • Should I pass something to the request, if yes what?

More generally how to handle this situation?

2

Answers


  1. Chosen as BEST ANSWER

    awannabeengineer was right. Here is a proof of concept (adaptation must be made on server side code after user authentication and info are retrieved).

    Server:

    fastify.post("/authcheck", async (request, reply) => {
      try {
        const idToken = request.body.idToken;
        console.log(idToken);
        const decodedToken = await firebase.auth().verifyIdToken(idToken);
        const uid = decodedToken.uid;
    
        // Get user data from Firebase
        const user = await firebase.auth().getUser(uid);
        console.log(user.displayName);
        return user; // DO SOMETHING ELSE
      } catch (error) {
        console.error("Error verifying ID token:", error);
        reply.code(401).send({ error: "Unauthorized access" });
      }
    });
    

    Frontend:

     async function sendTokenToServer() {
                try {
                  const idToken = await firebase
                    .auth()
                    .currentUser.getIdToken(/* forceRefresh */ true);
    
                  // Send token to your backend via HTTPS
                  const response = await fetch("/authcheck", {
                    method: "POST",
                    headers: {
                      "Content-Type": "application/json",
                    },
                    body: JSON.stringify({ idToken }),
                  });
    
                  if (!response.ok) {
                    throw new Error("Network response was not ok");
                  }
    
                  const data = await response.json();
    
                  // Handle server response here
                  console.log("User ID:", data.userId);
                } catch (error) {
                  // Handle error
                  console.error("Error:", error);
                }
              }
    
              sendTokenToServer();
    

    And yes I now use firebase admin on the server side ("firebase" is the instance on server).


  2. In order to verify a user server side, you will need to generate a JWT client side and then verify that on the server.
    First, on the client side generate IdToken

    Next, send along the token in your request to the server. You can use bearer authentication for this (send as HTTP header. Authorization: Bearer )

    On the server you can use any JWT library to verify the token.
    If you want to use the Firebase SDK then you must use the correct one.
    "firebase/compat/auth" is for client side. You need Firebase Admin SDK,
    here is the link on how to Verify ID tokens using the Firebase Admin SDK

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search