1

I have a nodjs app running that uses basic auth with the password details in a file generated by htpasswd. This is working fine.

What I'd like to do is run it over https. I can get it working with https fine, but can't seem to work out how to get the two working together, https + basic auth.

This is for a browser going to the server and sending a variable in the url. I've found a few solutions but many seem to focus on the server doing a outbound call to something else with basic auth.

This is the basic auth one.

    // Authentication module.
const auth = require('http-auth');
const basic = auth.basic({
    realm: "REALM.",
    file: __dirname + "/users.htpasswd"
});
const http = require('http');

const fs = require('fs');


var url = require('url');

const hostname = '0.0.0.0';
const port = 80;

const server = http.createServer(basic, (req, res) => {
  var url_parts = url.parse(req.url, true);
  var key = url_parts.query["name"];
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');

  fs.readFile(__dirname + '/basic.json', function (err, data) {
    if (err) {
      throw err;
    }

    table = JSON.parse(data.toString());

    var value = table[key];
    res.end(JSON.stringify({"group" : value}));
  });
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

And this is the https bit without the basic auth.

const https = require('https');
const fs = require('fs');

var url = require('url');

const hostname = '0.0.0.0';
const port = 443;

const options = {
  key: fs.readFileSync('star.pkey'),
  cert: fs.readFileSync('star.pem'),
};

const server = https.createServer(options, (req, res) => {
  var url_parts = url.parse(req.url, true);
  var key = url_parts.query["name"];
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');

  fs.readFile(__dirname + '/basic.json', function (err, data) {
    if (err) {
      throw err;
    }

    table = JSON.parse(data.toString());

    var value = table[key];
    res.end(JSON.stringify({"group" : value}));
  });
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Any help appreciated.

mickwombat
  • 11
  • 4

0 Answers0