仅通过Express框架对某些URL使用HTTP基本身份验证
我有一个使用Express框架和 http-auth 模块设计的node.js应用程序,如下所示:
I have a node.js application designed using the Express framework and the http-auth module, as follows:
var auth = require('http-auth');
var express = require('express');
// ...
var mywebapp = express();
// ...
if (usebasicauth) {
var basic = auth.basic({realm:"MyRealm", file:"/srv/config/passwd"});
mywebapp.use(auth.connect(basic));
}
mywebapp.use('/js', express.static(__dirname + '/files/js'));
mywebapp.use('/css', express.static(__dirname + '/files/css'));
// ...
但是,我不想保护/js
和/css
目录下的可用资产.这是我尝试做的:
However, I don't want to protect assets available under the /js
and /css
directories. This is what I tried doing:
if (usebasicauth) {
var basic = auth.basic({realm:"MyRealm", file:"/srv/config/passwd"});
mywebapp.use(function(req, res, next) {
if (/^\/(css|js)/.test(req.url)) {
next();
}
else {
auth.connect(basic);
}
});
}
尝试访问/css
和/js
下的URL可以正常进行;但是,其他URL永远不会加载.
Trying to access URLs under /css
and /js
work as expected; however, other URLs never load.
如何使其他URL正常工作?
How can I make other URLs work as expected?
mywebapp.use
的顺序很重要.
如果您有第一个mywebapp.use(auth.connect(basic));
,则它将用于每个请求
但是,如果您更改顺序,则它将传递静态信息,并且仅用于其后的内容.
The order of mywebapp.use
is important.
If you have first mywebapp.use(auth.connect(basic));
then it will be used for every request
but if you change the order it will pass statics and be only used for whatever is after it.
按照添加顺序对中间件功能进行处理.
所以下面应该做你想要的.
So following should do what you want.
// no auth for statics
mywebapp.use('/js', express.static(__dirname + '/files/js'));
mywebapp.use('/css', express.static(__dirname + '/files/css'));
// auth reguired from here
mywebapp.use(auth.connect(basic));
如果将mywebapp.use(auth.connect(basic));
放在express.static上方,它也会要求auth认证.
If you place mywebapp.use(auth.connect(basic));
above express.static it will reguire auth for it as well.
// auth reguired from here
mywebapp.use(auth.connect(basic));
// auth required for statics as well
mywebapp.use('/js', express.static(__dirname + '/files/js'));
mywebapp.use('/css', express.static(__dirname + '/files/css'));