2

我正在尝试使用http-auth模块设置一个简单的身份验证。

我已经创建了这个设置,但它不能正常工作。提示用户/通行证的对话框出现,但如果我关闭该对话框,应用程序将继续工作,也就是说,身份验证似乎不起作用。

似乎这不起作用,因为我已尝试将其设置http-auth为在我的静态文件夹中工作www

app.js的就是基于这个

这是我的设置:

'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'));
});
4

1 回答 1

2

如果您浏览http://localhost:4000/,您的示例将完美运行,点击取消后您会看到 401 消息,而不是您可以添加到/路由的内容(现在您没有路由处理程序)。

要使其适用于静态文件,您只需为静态文件启用身份验证,如下所示:

'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.

于 2016-09-25T20:35:07.510 回答