我想在显示 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');
}
});
如何在服务器端查看用户认证状态?
最佳答案
正如所建议的,有无数种方法可以对用户进行身份验证。 但我会用一个简单的例子来帮助你:
- 您应该有一个持久的用户列表,例如数据库。为了简单起见,我们将在代码中使用常量。
const express = require('express');
var jquery = require('jquery');
var admin = require("firebase");
const USER = {
email: "john@doe.com",
password: "12345"
}
- 有多种方法可以实现身份验证检查。我建议使用可以应用于各种路由的中间件:
const authenticate = (req, res, next) => {
// parse the user out of your request
// e.g with bodyparser -> see npm
if (req.body.email === USER.email && req.body.password === USER.password) {
next()
} else {
res.send({ status: 401 });
}
}
- 将此中间件应用于您要保护的路由或所有路由
// all routes
app.use(authenticate)
// certain route
app.get('/someRoute', authenticate, (req, res)) => {
// only successful authenticated user
// (in this case: john@doe.com) will
// have access to this route.
// ... code
}
可以使用 cookie、jwt 等扩展此模式,当然还有可以存储注册用户的数据库。
关于javascript - 如何在服务器端查看用户认证状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54787275/