Skip to content

Instantly share code, notes, and snippets.

@gevorg
Last active September 22, 2023 09:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gevorg/7168d5f02c1ca5362b2a to your computer and use it in GitHub Desktop.
Save gevorg/7168d5f02c1ca5362b2a to your computer and use it in GitHub Desktop.
Exclude specific path from http-auth
// 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);
// Log URL.
console.log("Server running at http://127.0.0.1:1337/");
@llcoollasa
Copy link

llcoollasa commented Nov 11, 2020

This is also working

const authorizer = (username: string, password: string) => {
const userMatches = basicAuth.safeCompare(username, 'admin');
const passwordMatches = basicAuth.safeCompare(password, 'password');

    return userMatches && passwordMatches;
};

const basic = basicAuth({
    authorizer,
});

app.use((req, res, next) => {
    if (req.path === '/your-custom-path') {
        next();
    } else {
        basic(req, res, next);
    }
});`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment