2

I need some guidance to pass a static header to auth_request in nginx.
My locations config is as below:

location = /auth {
  internal;     
  proxy_pass http://authserver.com:8009/auth;
  proxy_pass_request_body off;
  proxy_set_header Content-Length "";
  proxy_set_header X-Original-URI $request_uri;
}

And my subrequest looks like below:

location = /app/finance/ {
  proxy_pass_request_headers      on;
  # Custom header to be added
  proxy_set_header CallType "MAJOR";
  auth_request /auth;
  error_page 401 =401 /auth;      
  proxy_pass http://myaddservice.com:8080/finance/;
}

I need to pass CallType header to auth_request.I have tried with add_header, proxy_set_header but it didnt work.
I have a Rest Api to authenticate behind auth_request which is expecting the CallType header.
I cannot make it pass as a part of api header because its an internal process.

1 Answers1

2

You can try this:

location = /auth {
  internal;     
  proxy_pass http://authserver.com:8009/auth;
  proxy_pass_request_body off;
  proxy_set_header Content-Length "";
  proxy_set_header X-Original-URI $request_uri;
  proxy_set_header CallType $calltype;
}

location = /app/finance/ {
  set $calltype "MAJOR";
  proxy_pass_request_headers      on;
  auth_request /auth;
  error_page 401 =401 /auth;      
  proxy_pass http://myaddservice.com:8080/finance/;
}

If the auth request will be called from some other location, the $calltype variable would have an empty value and the CallType header won't be set at all (nginx does not set the header if an empty value is passed as the parameter to add_header or proxy_set_header directives).

Ivan Shatsky
  • 13,267
  • 2
  • 21
  • 37
  • Is variable scope per-request? – bobah Feb 07 '22 at 20:06
  • @bobah Yes, it is. If you need to share some data with several requests, it can be a non-trivial task and I doubt it can be solved without additional third party modules. If you really need to, take a look at [this](https://github.com/openresty/lua-nginx-module#ngxshareddict). – Ivan Shatsky Feb 07 '22 at 20:12
  • I needed it per-request, just wanted to be sure it’s not leaking anywhere else, perfect! – bobah Feb 08 '22 at 20:36