简体   繁体   English

如何检查用户是否在Firebase和Express / Node.js中通过了身份验证?

[英]How to check if user is authenticated in Firebase and Express/Node.js?

If I have a page that can only be accessed by authenticated users, how do I check if a user is authenticated or not? 如果我的页面只能由经过身份验证的用户访问,如何检查用户是否经过身份验证?

I tried using (firebase.auth().currentUser !== null) but I am getting an error saying: TypeError: firebase.auth is not a function 我尝试使用(firebase.auth().currentUser !== null)但出现错误消息: TypeError: firebase.auth is not a function

I have the following configuration: 我有以下配置:

const express = require('express'),
      firebase = require('firebase'),
      app = express();

app.use(express.static("/public"));

var config = {
   apiKey: "xxxx",
   authDomain: "xxxx",
   databaseURL: "xxxx",
   projectId: "xxxx",
   storageBucket: "xxxx",
   messagingSenderId: "xxxx"
};

firebase.initializeApp(config); 

app.get("/dashboard", (request, response) => {
   if (firebase.auth().currentUser !== null){
       response.render("dashboard.ejs")
   }
   else{
       response.render("login.ejs");
   }
});

Your code is in an Express app, which means it runs on the server. 您的代码在Express应用中,这意味着它在服务器上运行。 The Firebase SDK you're using is meant for use on client devices, and won't work well in your Express environment. 您使用的Firebase SDK仅适用于客户端设备,在Express环境中无法正常使用。 There is no concept of a "current user" on the server. 服务器上没有“当前用户”的概念。 Of course a user ID can be passed to the server with each request, but the server itself is stateless. 当然,可以将每个请求的用户标识传递给服务器,但是服务器本身是无状态的。

In your Express server you'll want to use the Firebase Admin SDK. 在您的Express服务器中,您将要使用Firebase Admin SDK。 Have a look at this Cloud Functions sample on how to build an authenticated endpoint . 查看此Cloud Functions示例,了解如何构建经过身份验证的端点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM