Search code examples
node.jshttp-authentication

htttp auth with node and express


I have set up http auth on my express website however I only want one specific url to be authenticated. '/admin'. Currently all area's require authentication other than the root, which is odd.

My Code:

var auth = require("http-auth");
var basic = auth.basic({
    authRealm: "Private area",
    authFile: __dirname + "/htpasswd",
    authType: "basic"
});

app.use(auth.connect(basic));

app.get('/admin', function(request, response) {
    response.render('index');
});

So how can I make authentication specific for just /admin - I have another url /api which i mean to not require the authentication.

Thanks


Solution

  • You're applying the middleware to each request by using use.

    Apply it to only the routes you need by using

    var auth = require("http-auth");
    var basic = auth.basic({
        authRealm: "Private area",
        authFile: __dirname + "/htpasswd",
        authType: "basic"
    });
    
    app.get('/admin', auth.connect(basic), function(request, response) {
        response.render('index');
    });