Nginx – how authenticated multiple subdomains in nginx with one login

authenticationnginxsingle-sign-onsubdomain

we've got app consisting of several parts. Each part is running on it's subdomain (nginx site). We would like to hide access of dev env behind some shared auth, where first login on whatever of subdomains gonna grant access also for others.

Our first idea was put nginx proxy site containing all domains ahead and set basic auth there and then proxy pass communication. Partially it was working. Problem is that basic auth is binded to domain name, so after loging one subdomain, I must put credentials for each on first access.

Simplified example configuration we used, but it did not work desired way.

server {
    listen 443 ssl http2;

    server_name paapi-xy.example.com;

    access_log /var/www/access_api_443.log;
    error_log /var/www/error_api_443.log debug;

    ssl_certificate /etc/ssl/example/example.com.chained.crt;
    ssl_certificate_key /etc/ssl/example/example.com.key;

    ssl_session_timeout 1d;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    root /var/www/html;

    location / {
        try_files $uri /index.api.html;
    }
}

server {
    listen 443 ssl http2;

    server_name pawww-xy.example.com;

    access_log /var/www/access_www_443.log;
    error_log /var/www/error_www_443.log debug;

    ssl_certificate /etc/ssl/example/example.com.chained.crt;
    ssl_certificate_key /etc/ssl/example/example.com.key;

    ssl_session_timeout 1d;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    root /var/www/html;

    location / {
        try_files $uri /index.www.html;
    }        
}

server {
    listen 443 ssl http2;

    server_name paapi.example.com pawww.example.com;

    access_log /var/www/access_proxy_443.log;
    error_log /var/www/error_proxy_443.log debug;

    ssl_certificate /etc/ssl/example/example.com.chained.crt;
    ssl_certificate_key /etc/ssl/example/example.com.key;

    ssl_session_timeout 1d;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    root /var/www/html;

    set $xheader "someignoredvalue";

    location / {
        satisfy any;

        auth_basic example_auth;
        auth_basic_user_file /var/www/.htpasswd;

        include proxy_params;

        if ($host = paapi.example.com) {
            proxy_pass                    https://paapi-xy.example.com;
            set $xheader paapi-xy.example.com; 
        }

        if ($host = pawww.example.com) {
            proxy_pass                    https://pawww-xy.example.com;
            set $xheader pawww-xy.example.com; 
        }

        proxy_set_header Host $xheader;
    } 
}

Does anybody has some other idea how to do that, kind of SingleSignOn.

Best Answer

You could try to use the auth_basic module at the http context level to apply it to every virtualhost:

http {

    auth_basic             "Administrator’s Area";
    auth_basic_user_file   conf/htpasswd;

    server { ... }
    server { ... }
    server { ... }
}