Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Express protect route by password

Tags:

node.js

I have a small application built with NodeJS. The users have the option to protect their routes by user/password, which I achieved by simple custom basic auth mittleware:

bas64: RequestHandler = (req: express.Request, res: express.Response, next: express.NextFunction) => {
  const b64auth = (req.headers.authorization || '').split(' ')[1] || '';
  if (!checkCredentials(b64auth)) {
    res.set('WWW-Authenticate', 'Basic realm="401"');
    return res.status(401).send('Authentication required.');
  }
  next();
});

Now I got the feedback, that the user is not required and a simple password would be easier. So I'm wondering, if it is possible to achieve the same without username. I know it is not possible to remove the username from WWW-Authenticate. And of course I can display a text, that the username can be empty. But I don't like this solution. Is there maybe any other solution?

like image 541
Nico Schuck Avatar asked Feb 20 '26 13:02

Nico Schuck


1 Answers

Use a middleware and cookie

import express from "express";
import cookieParser from "cookie-parser";


const authenticate = (req, res, next) => {
  const reject = () => {
    res.setHeader("www-authenticate", "Basic");
    res.sendStatus(401);
  };

  const authorization = req.headers.authorization;
  const session = req["signedCookies"].session;

  if (req.method === "GET" && session === "authenticated") {
    return next();
  }

  if (!authorization) {
    return reject();
  }

  const [username, password] = Buffer.from(
    authorization.replace("Basic ", ""),
    "base64"
  )
    .toString()
    .split(":");

  if (!(username === "username" && password === "password")) {
    return reject();
  }

  res.cookie("session", "authenticated", {
    signed: true,
    maxAge: 60 * 60 * 1000,
    httpOnly: true,
  });

  next();
};

const app = express();
app.use(cookieParser("cookie-password"));
app.use(authenticate);

The code above will authenticate the user when they load a get route and store cookie for 1 hour if the username and password matches.

like image 166
iAmServer Avatar answered Feb 27 '26 04:02

iAmServer