Basic Auth in Express for NodeJS

Security is a huge issue for web services. With everything including your toaster getting an REST API lately, there are a lot of attack vectors for hackers that never were possible before.

One way to provide a reasonable amount of security is to protect your services with HTTP built in authentication, basic auth. It's not without its faults. It's often stored at the browser level and never really expires. However, over HTTPS, it provides a level of security that is infinitely better than having none at all.

I've been building a lot of REST services over express lately. It makes a lot of stuff really easy to do, including basic auth.

const basicAuth = require("basic-auth");
const auth = (req, res, next) => {
    const unauthorized = (res) => {
        res.set("WWW-Authenticate", "Basic realm=Authorization Required");
        return res.sendStatus(401);
    };
    const user = basicAuth(req);
    if (!user || !user.name || !user.pass) {
        return unauthorized(res);
    };
    if (user.name === "admin" && user.pass === "changethis") {
        return next();
    } else {
        return unauthorized(res);
    };
};

You can just include this snippet in your server and then include a reference to it in each endpoint you want to be protected, and you will have it be protected by basic auth.

app.get("/endpoint/", auth, (req, res) => res.send("OK"));

You can see it in a larger context on my github page.