user49740
user49740

Reputation: 393

Nginx optional auth_request

I want to make nginx reject clients with invalid credentials, while still allowing clients with no Authorization header at all.

Current config:

server {
    listen 443 ssl;
    server_name ...;

    proxy_http_version 1.1;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    location / {
        proxy_pass http://localhost:8080;
    }
}

If auth_request worked inside an if, this would have solved my problem:

    location / {
        proxy_pass http://localhost:8080;
        if ($http_authorization) {
            auth_request /login;
        }
    }

Upvotes: 3

Views: 1802

Answers (1)

user49740
user49740

Reputation: 393

This seems to work:

    proxy_http_version 1.1;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    location /__auth {
        internal;
        proxy_pass http://localhost:8080/login;
    }

    location / {
        if ($http_authorization) {
            rewrite ^(.*)$ /_auth$1 last;
        }
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Logged-In "";
        proxy_pass http://localhost:8080;
    }

    location ~ /_auth(.*) {
        internal;
        set $gooduri $1;
        auth_request /__auth;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Logged-In 1;
        proxy_pass http://localhost:8080$gooduri;
    }

The question remains open to better solutions.

Upvotes: 1

Related Questions