Nodejs + firebase: How to check if user is server side authenticated
P粉493313067
P粉493313067 2023-09-08 14:13:39
0
2
508

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?

  • Is there a Firebase function that I'm not aware of that can retrieve the current user information?
  • Should I pass something to the request? If so, what content is conveyed?

How to deal with this situation more generally?

P粉493313067
P粉493313067

reply all(2)
P粉360266095

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

P粉141911244

In order to authenticate users server-side, you need to generate the JWT client and then validate it on the server. First, generate IdToken p> 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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!