简体   繁体   English

为什么 http-auth 不适用于 express.static 中间件?

[英]Why http-auth does not work with express.static middleware?

I'm trying to setup a simple auth using http-auth module.我正在尝试使用http-auth模块设置一个简单的身份验证

I've created this setup but it's not working properly.我已经创建了这个设置,但它不能正常工作。 The dialog prompting the user/pass show up but if I close the dialog the app continues to work, that is, the auth don't seem to be working.提示用户/密码的对话框出现,但如果我关闭该对话框,应用程序将继续工作,也就是说,身份验证似乎不起作用。

Seem that's not working because I've tried to setup this http-auth to work in my static folder www .似乎这不起作用,因为我已尝试将此http-auth设置为在我的静态文件夹www

My app.js is based on this one .我的app.js基于这个

Here is my setup:这是我的设置:

'use strict';

var express = require('express');
var app = express();
var auth = require('http-auth');

app.use(express.static('www'));

var basic = auth.basic({
  realm: 'SUPER SECRET STUFF'
}, function(username, password, callback) {
  callback(username == 'username' && password == 'password');
});

app.use("/", auth.connect(basic));

app.set('port', (process.env.PORT || 4000));
app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

Your example works perfectly if you browse http://localhost:4000/ , after hitting cancel you see 401 message instead of content that you could add to / route (now you don't have route handler for it).如果您浏览http://localhost:4000/ ,您的示例完美运行,点击取消后,您会看到 401 消息而不是您可以添加到/路由的内容(现在您没有路由处理程序)。

To make it work for static files you just need to enable authentication for static files also, something like this will do it:要使其适用于静态文件,您只需要为静态文件启用身份验证,如下所示:

'use strict';

var express = require('express');
var app = express();
var auth = require('http-auth');

var basic = auth.basic({
    realm: 'SUPER SECRET STUFF'
}, function(username, password, callback) {
    callback(username == 'username' && password == 'password');
});

app.use(auth.connect(basic));
app.use(express.static('www'));

app.set('port', (process.env.PORT || 4000));
app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});

As you may notice authentication middleware auth.connect should be declared before static file middleware express.static and without route prefix as your static file middleware does not have route prefix.您可能会注意到身份验证中间件auth.connect应该在静态文件中间件express.static之前声明并且没有路由前缀,因为您的静态文件中间件没有路由前缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM