I need to add conditional authorization to a redirection in Nginx, only when one defined url parameter is received (t in this case). And the value of this parameter has to be passed to the authentication server as a Bearer token in the Authorization header.
I have tried using ideas taken from here, but I can't get it to work.
Let me explain what I want to achieve with an example.
My server receive: /sec/foo proxy to http://localhost:3001/foo
but if it receives: /sec/foo?t=valid_token, I need proxy to http://localhost:3001/foo?t=valid_token after previously validating the token with service http://validate:8080, which can expect as a Bearer header (also works if the token is received as parameter).
set $val "";
location /sec/ {
# idea from https://stackoverflow.com/a/69961396/2249460
if ($arg_t != "") {
set $val $arg_t;
rewrite ^ /__sec__$uri last;
}
proxy_pass http://localhost:3001/;
}
location /__sec__ {
internal;
# I tried to save token value and set header en both location. Didnt work
# set $val $arg_t;
# proxy_set_header Authorization "Bearer $arg_t";
rewrite ^/__sec2__(?<realurl>/.*)$ $realurl break;
auth_request /_test_auth;
error_page 401 403 500 =401 /error/401;
proxy_pass http://localhost:3001/;
}
# Auth location shared with other locations
location /_test_auth {
internal;
set $val_auth $http_authorization;
if ($val != '') {
set $val_auth "Bearer $val";
}
proxy_pass http://validate:8080;
proxy_http_version 1.1;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header Authorization $val_auth;
proxy_ignore_headers Expires Cache-Control Vary Set-Cookie;
proxy_cache cache_zone;
proxy_cache_key $val_auth;
proxy_cache_valid any 1m;
}
I tried to do the same using the njs module, and I also obtained negative results.
location /sec/ {
auth_request /_js_auth;
proxy_pass http://localhost:3001/;
}
location /_js_auth {
internal;
# I need to set the Authorization header, but I dont have the token
proxy_set_header Authorization "Bearer $arg_t";
js_content auth.main;
}
location /_test_auth as defined above
auth.js content:
function main(r) {
if (r.args.t !== undefined) {
r.subrequest('/_test_auth', function (reply){
// I need pass the arg value as a header or set in a variable to use in proxy_set_header
r.return(reply.status);
});
}
r.return(200);
}
export default { main };
Any suggestions?