Using the basic HTTP protocol for specific URLs using the Express platform only

I have a node.js application developed 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')); // ... 

However, I do not want to protect the assets available in the /js and /css directories. This is what I tried to do:

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

Attempting to access URLs under /css and /js works as expected; however, other URLs never load.

How to make other urls work as expected?

+5
source share
2 answers

The order of mywebapp.use important. If you have the first mywebapp.use(auth.connect(basic)); , then it will be used for each request, but if you change the order, it will go through the statics and will be used only for what is after it.

Middleware functions are processed to be added.

So the 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)); 

If you post mywebapp.use(auth.connect(basic)); above express.static, it will also regress for it.

 // 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')); 
+8
source

You can also do something like this https://gist.github.com/gevorg/7168d5f02c1ca5362b2a#file-specific-path-js

 // Express module. var express = require('express'); // Authentication module. var auth = require('http-auth'); var basic = auth.basic({ realm: "Simon Area.", file: __dirname + "/../data/users.htpasswd" // gevorg:gpass, Sarah:testpass ... }); // Application setup. var app = express(); app.use(function(req, res, next) { if ('/specific/path' === req.path) { next(); } else { (auth.connect(basic))(req, res, next); } }); // Setup route. app.get('/', function(req, res){ res.send("Hello from express - " + req.user + "!"); }); // Setup guest route. app.get('/specific/path', function(req, res){ res.send("Hello from express - guest!"); }); // Start server. app.listen(1337); 
+3
source

Source: https://habr.com/ru/post/1239259/


All Articles