I want to have my nginx proxy perform a subrequest for authentication only if the client is not already authenticated. The conditional part is where I am stuck. How can I craft a configuration so that the client is only authenticated once per session?
I am able to successfully perform an auth_request to Apache and pull back the headers I want to pass on to the back-end, but this is occurring on every request and is expensive.
In the example here, my goal is to only perform the auth_request if the "Authorization" header is missing or empty or alternately a cookie containing the token
# DEFAULT BACKEND
location / {
proxy_pass_request_body off;
if ($http_authorization ~* '')
{
rewrite ^(.*)$ /__login;
}
if ($user !~* "([aa-zZ]+)@example.com")
{
}
if ($http_cookie !~* "(auth_cookie=([aa-zZ]+)@example.com)")
{
add_header Set-Cookie "auth_cookie=$user;domain=.example.com;Max-Age=3000";
}
proxy_pass_header x-webauth-user;
proxy_pass_header Set-Cookie;
proxy_pass http://example.com:6762/;
}
location /__login { internal;
auth_request /auth;
auth_request_set $user $upstream_http_x_webauth_user;
set $xuser $user;
add_header Auth-User $user;
proxy_set_header User-Name $user;
proxy_set_header Authorization $http_authorization;
#proxy_pass_header x-webauth-user;
#proxy_pass_header Set-Cookie;
proxy_pass http://example:6762/;
access_log /etc/nginx/login_debug.log;
}
location = /auth{
internal;
proxy_pass http://example.com:81/;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-for $proxy_add_x_forwarded_for;
#proxy_pass_header Set-Cookie;
#proxy_pass_header x-webauth-user;
}
The Auth-User header gets lost on all requests after the first and the cookie never seems to get set, beyond that the page doesn't actually seem to render in a browser. I am obviously doing something very wrong, could some please help me figure this out.