search

Home  >  Q&A  >  body text

Nodejs + firebase: How to check if user is server side authenticated

Users authenticate on the client side using firebase sdk.

On the server side, there is nodejs and sdk is also installed. This server code works because I can use the database:

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 works.

This 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",
 });
});

User variables are always empty.

What is the correct way to handle this problem?

How to deal with this situation more generally?

P粉493313067P粉493313067495 days ago591

reply all(2)I'll reply

  • P粉360266095

    P粉3602660952023-09-09 13:15:25

    aannabeengineer is right. This is a proof of concept (server side code must be adjusted after user authentication and retrieving information).

    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" });
      }
    });

    front end:

    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();

    Yes, I am currently using firebase admin on the server side ("firebase" is the instance on the server).

    reply
    0
  • P粉141911244

    P粉1419112442023-09-09 12:18:05

    In order to authenticate users server-side, you need to generate the JWT client and then validate it on the server. First, generate IdToken on the client side

    Next, send the token in the request to the server. You can use Bearer Authentication for this (sent 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, you must use the correct SDK. "firebase/compat/auth" is for clients. You need the Firebase Management SDK, The following link explains how to Use the Firebase Admin Validation ID Token SDK

    reply
    0
  • Cancelreply