如何检查用户是否在Firebase和Express/Node.js中通过了身份验证? [英] How to check if user is authenticated in Firebase and Express/Node.js?

查看:75
本文介绍了如何检查用户是否在Firebase和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?

我尝试使用(firebase.auth().currentUser !== null),但收到一条错误消息:TypeError: firebase.auth is not a function

I tried using (firebase.auth().currentUser !== null) but I am getting an error saying: TypeError: firebase.auth is not a function

我有以下配置:

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

推荐答案

您的代码在Express应用程序中,这意味着它在服务器上运行.您使用的Firebase SDK只能在客户端设备上使用,在Express环境中无法正常使用.服务器上没有当前用户"的概念.当然,可以将每个请求的用户ID传递给服务器,但是服务器本身是无状态的.

Your code is in an Express app, which means it runs on the server. The Firebase SDK you're using is meant for use on client devices, and won't work well in your Express environment. 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.

在Express服务器中,您将要使用Firebase Admin SDK.看看此有关如何构建经过身份验证的端点的Cloud Functions示例.

In your Express server you'll want to use the Firebase Admin SDK. Have a look at this Cloud Functions sample on how to build an authenticated endpoint.

这篇关于如何检查用户是否在Firebase和Express/Node.js中通过了身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆