Node 和 Express 4 的基本 HTTP 身份验证 [英] Basic HTTP authentication with Node and Express 4
本文介绍了Node 和 Express 4 的基本 HTTP 身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
看起来使用 Express v3 实现基本的 HTTP 身份验证很简单:
It looks like implementing basic HTTP authentication with Express v3 was trivial:
app.use(express.basicAuth('username', 'password'));
版本 4(我使用的是 4.2)虽然删除了 basicAuth
中间件,所以我有点卡住了.我有以下代码,但它不会导致浏览器提示用户输入凭据,这正是我想要的(以及我想象的旧方法所做的):
Version 4 (I'm using 4.2) removed the basicAuth
middleware, though, so I'm a little stuck. I have the following code, but it doesn't cause the browser to prompt the user for credentials, which is what I'd like (and what I imagine the old method did):
app.use(function(req, res, next) {
var user = auth(req);
if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
res.writeHead(401, 'Access invalid for user', {'Content-Type' : 'text/plain'});
res.end('Invalid credentials');
} else {
next();
}
});
推荐答案
我用的是原代码 basicAuth
找到答案:
I used the code for the original basicAuth
to find the answer:
app.use(function(req, res, next) {
var user = auth(req);
if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
res.end('Unauthorized');
} else {
next();
}
});
这篇关于Node 和 Express 4 的基本 HTTP 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文