我目前正在使用构建一个网络应用程序Node.js
and Express.js
.
我正在寻找一种方法,在我的主目录中使用用户名和密码进行简单的服务器端身份验证app.js
正在监听的文件post
请求于http://www.domain.com/login
:
app.js
app.post('/login', function(req, res) {
// some server-side code for a username and password
}
在客户端,我有一个带有用户名和密码的简单登录表单。该表单将发布到服务器:
索引.html
<form method="post" action="/login">
<input type="text" id="user" name="user" />
<input type="password" id="pass" name="pass" />
<button type="submit">Login</button>
</form>
我希望实现这一目标without使用任何ExpressJS
插件。
Edit:所以我的问题是,如何在 ExpressJS 和 NodeJS 中实现简单的用户名和密码身份验证?
通过使用 ExpressJS 会话,您可以保存会话 cookie。您需要 cookieParser 和会话存储。但是,如果您不想扩展此 ExpressJS 功能(这是我从您的消息中了解到的),您应该使用令牌或秘密临时字符串来管理您自己的会话。
尽管我强烈建议您使用 ExpressJS 会话,但在没有 ExpressJS cookie 的情况下您应该这样做。
- 每次登录时,创建一个唯一的令牌并将其存储以供将来查找。
- 对于每个请求,从客户端发送该令牌并在服务器上检查它。如果令牌无效,则重定向到登录
这是登录代码示例:
app.post("/login", function(req, res) {
if(req.body.username && req.body.password) {
// check username and password
if(authenticated) {
// create a token and store it with the current date (if you want it to expire)
var token = generateAndStoreRandomString(req.body.username);
res.redirect("http://your.domain/path?token=" + token);
return;
}
// Do something if username or password wrong
}
// Do something if no username or password
});
现在,根据每个请求:
app.get("somePath", function(req, res) {
if(!req.query.token) {
res.redirect("http://your.domain/login");
return;
}
// Check token in database, if it exists and it hasn't expired
if(!authenticated) {
res.redirect("http://your.domain/login");
return;
}
// The user is authenticated. Do the actions required by "somePath"
});
尝试让进程每隔一段时间清理一次过期的令牌,因为它们最终会累积起来。如果你想使用 ExpressJS cookieParser 和会话存储,有很多文章和示例。如果您遇到这些问题,请发布另一个问题。
我将重复一遍,尝试使用 Express JS 会话。如果您使用 http 而不是 https,此方法很容易被黑客攻击。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)