Basic Authentication with Nginx and NodeJS

Wed 22 May 2019

Introduction

This is a short post on how to use Basic Authentication on an Nginx proxy and pass the credentials to your NodeJS backend.

Basic Authentication

I’m assuming you have a basic auth database. You can read more about the layout in the Apache Documentation

I’m also assuming you know what you’re doing:

  1. You are using Basic Authentication for a good reason behind https.
  2. You’re using http but you have your reasons.
  3. You want to have some authentication on your server and you need to pass it on to your NodeJS backend application.

All you need to support basic authentication is a password database containing the username and hashed password pairs.

server {
    listen 80;
    server_name example.com;
    root /documents/web;
        auth_basic "Document Services: Windows Password";
        auth_basic_user_file /etc/nginx/conf.d/htpasswd;

    location /api/ {
        add_header Set-Cookie "user=$remote_user";
        proxy_pass http://example.com:3000;
    }
}

Nginx Cookies

add_header Set-Cookie "user=$remote_user";

Pass the Cookie Value to NodeJS

This function is in a utils.js file for my application.

module.exports.getCookies = function(s) {
    const cookies = {};
    s.split(';').forEach(function(cookie) {
        let parts = cookie.match(/(.*?)=(.*)$/);
        cookies[ parts[1].trim() ] = (parts[2] || '').trim();
    });
    return cookies;
};

Then call the function and use the value:

exports.testme = function(req, res) {
    const cookies = getCookies(req.headers.cookie);
    const tmpdata = request.body;
    tmpdata.user = cookies.user;
    res.json(tmpdata);
}

Category: NodeJS Tagged: how-to web

Comments