When we want to add authentication to a website really quick, the first solution that comes to mind is Basic access authentication.

However, in my experience, basic auth doesn’t work well in some cases, especially when you are using http instead of https, or your frontend is sending a lot of XHRs. For some reasons, either the browser basic auth dialog pops up multiple times, disrupting the user experience, or XHRs will fail with 401. Another downside is, it’s not so convenient to send the content to your users. You will have to give them the URL and the username / password, and ask them to copy & paste. It would be more convenient if they could simply scan a QR code or enter a single URL to log in.

I recently discovered a method that allowed us to accomplish this with a basic nginx configuration.

  1. A GET request to /login?password=[password]&redirect=[url] will set cookies password to [password] and send a 302 redirect response to [url].
  2. For all other requests, it will be asserted that the password cookie matches [password], otherwise a 401 response is returned.

Here is a sample nginx config:

http {
    map $cookie_password $is_valid_password {
        default 0;
        "your-password-here" 1;
    }
    
    server {
        listen       80;
        server_name  my-server.com;
        root       /path/to/root;
        index index.html;

        location = /login {
            if ($request_method != GET) {
                return 405;
            }

            if ($arg_password = "") {
                return 400;
            }

            if ($arg_redirect = "") {
                return 400;
            }

            add_header Set-Cookie "password=$arg_password; Path=/; HttpOnly";
            return 302 $arg_redirect;
        }

        location / {
            if ($is_valid_password != 1) {
                return 401;
            }

            # Your normal configuration for handling other requests goes here
            # e.g., proxy_pass, root, etc.
        }
    }
}

Now, you only need to send this URL

http://my-server.com/login?password=your-password-here&redirect=/some/page

to your user.

What are your thoughts on this technique?