看起来用Express v3实现基本的超文本传输协议身份验证很简单:
app.use(express.basicAuth('username', 'password'));
版本4(我使用的是4.2)去掉了basicAuth
中间件,所以我有点卡住了。我有以下代码,但它不会使浏览器提示用户输入凭据,这正是我想要的(我想旧方法也是这样做的):
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();
}
});
发布于 2014-05-13 02:37:46
我使用了原始basicAuth
的代码来找到答案:
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();
}
});
发布于 2014-06-26 04:20:35
很多中间件都是从v4的Express核心中提取出来的,并放在不同的模块中。基本的身份验证模块在这里:https://github.com/expressjs/basic-auth-connect
您的示例只需更改为:
var basicAuth = require('basic-auth-connect');
app.use(basicAuth('username', 'password'));
发布于 2014-07-08 18:04:47
我在express 4.0中用http-auth更改了基本身份验证,代码是:
var auth = require('http-auth');
var basic = auth.basic({
realm: "Web."
}, function (username, password, callback) { // Custom authentication method.
callback(username === "userName" && password === "password");
}
);
app.get('/the_url', auth.connect(basic), routes.theRoute);
https://stackoverflow.com/questions/23616371
复制相似问题