Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

node.js - Cannot use basic authentication while serving static files using express

Using the Express framework for node.js, I'm trying to serve up static files contained in a directory while also putting basic authentication on it. When I do so, I am prompted for the username and password (as expected), but after I correctly enter them, I'm given a 404. If I remove the authentication check and serve up the same directory, I actually get the pages contained within it.

Here's a quick server I whipped up as a proof-of-concept:

var express = require('express');

var app = express();

var auth = express.basicAuth(function(user,pass) {
  return 'user' === user && 'pass' === pass;
});

app.use('/admin', auth, express.static(__dirname + '/admin'));
app.use('/adminNoAuth', express.static(__dirname + '/admin'));

app.listen(8082);

When I hit localhost:8082/admin I get the username/password, then a 404. When I hit localhost:8082/adminNoAuth it serves up the page.

I'm using Express 3.4.7 and node.js 0.10.22.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

app.use doesn't let you chain middlewares in that way. The various app.VERB functions do, but app.use doesn't. That's for one middleware at a time.

If you split the 2 middlewares out into separate calls, you should get the results you want:

app.use('/admin', auth)
app.use('/admin', express.static(__dirname + '/admin'));

EDIT

As of express version 4.x you can pass in multiple middlewares as an array, or arguments, or mixture of both into app.use. Making static files authorization safe would now be:

app.use( "/admin", [ auth, express.static( __dirname + "/admin" ) ] );

But both ways are still perfectly valid.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...