No nginx basic auth with either network or cookie set

  • Christian Stocker

For an internal tool, we'd like to allow access if you either coming from one of our office networks or you have a certain cookie set. If both are not satisfied, just show the usual basic auth dialog. And set that cookie, once you were allowed to access the page.

We wanted to do that in nginx and not the tool itself, as it looked like easier to do, especially since the tool didn't have any authentication at all yet. Unfortunately it wasn't that straight forward, but we found a working solution and wanted to share that.

map $cookie_letmein $mysite_hascookie {
  "someRandomValue" "yes";
  default           "no";
}

geo $mysite_geo {
  192.168.0.0/24 "yes": #some network which should have access
  10.10.10.0/24  "yes": #some other network which should have access
  default        "no";
}

map $mysite_hascookie$mysite_geo $mysite_authentication{
  "yesyes" "off";  #both cookie and IP are correct  => OK
  "yesno"  "off"; #cookie is ok, but IP not  => OK
  "noyes"  "off";  #cookie is not ok, but IP is ok => OK
  default  "Your credentials please"; #everythingles => NOT OK
}

server {
  listen 80;
  server_name mysite.example.org;
  location / {
    auth_basic  $mysite_authentication;
    auth_basic_user_file  htpasswd/mysite;
    add_header Set-Cookie "letmein=someRandomValue;max-age=3153600000;path=/"; #set that special cookie, when everything is ok
    proxy_pass http://127.0.0.1:8000/;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $remote_addr;
  }
}

Hope it helps anyone and saves them some time.


Tell us what you think