简体   繁体   中英

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

I'm trying to setup a simple auth using http-auth module.

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 .

My app.js is based on this one .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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