首页 > 解决方案 > 如何在服务器端检查用户身份验证状态

问题描述

我想在显示 html 页面之前检查用户身份验证

我的 server.js 文件是这样的

const express = require('express');
var jquery = require('jquery');
var admin = require("firebase");

const app = express();

app.use(express.static(__dirname + '/public'));



var serviceAccount = require("firebasekey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://23442344114.firebaseio.com"
});

var ref = admin.app().database().ref();
 

app.get(['/','/index.html'], function(req, res) {
	res.sendFile(__dirname + '/public/index.html');
 
 });


app.get(['/dash' ], function(req, res) {
	res.sendFile(__dirname + '/public/dash/index.html');
  
 });
 
 

在呈现页面之前,如何检查用户是否首先在服务器端进行了身份验证;例如,

 app.get(['/dash' ], function(req, res) {
      //check if the user is authenticated

     if auth == true {
    res.sendFile(__dirname + '/public/dash/index.html');
     } else{
            res.sendFile(__dirname + '/public/login.html');

     }

 });

如何检查服务器端的用户认证状态?

标签: javascripthtmlexpressfirebase-authentication

解决方案


您应该阅读有关 JWT 和 OAuth 等身份验证方法的信息。您可以使用中间件来检查特定用户是否经过身份验证。你可以为这个像护照一样的图书馆。您可以像这样创建自己的路由器级中间件。

let middleware = function (req, res, next) {
   //Do your checking...
   next();
};

app.get(['/dash' ],middleware, function(req, res) {
   //check if the user is authenticated

   if auth == true {
       res.sendFile(__dirname + '/public/dash/index.html');
   } else {
       res.sendFile(__dirname + '/public/login.html');
   }
});

推荐阅读