Node和Express的基本HTTP认证4 [英] Basic HTTP authentication with Node and Express 4
本文介绍了Node和Express的基本HTTP认证4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
看起来像使用Express v3实现基本的HTTP身份验证是微不足道的:
app.use(express.basicAuth('username ','password'));
版本4(我使用4.2)删除了 basicAuth
中间件,但是,我有点卡住了。我有以下代码,但它不会导致浏览器提示用户凭据,这是我想要的(我想象的旧方法):
$ $ $ $ $ $ $ $ $ $ $ $
如果(用户= == undefined || user ['name']!=='username'|| user ['pass']!=='password'){
res.writeHead(401,'Access invalid for user' {'Content-Type':'text / plain'});
res.end('无效的凭证');
} else {
next();
}
});
解决方案
我使用原始代码 basicAuth
来找到答案: / p>
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();
}
});
It looks like implementing basic HTTP authentication with Express v3 was trivial:
app.use(express.basicAuth('username', 'password'));
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();
}
});
解决方案
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的基本HTTP认证4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文