How do you send an auth_request to a variable URI in nginx?

2.7k Views Asked by At

I am trying to use the auth_request module to check whether a user is allowed to access a certain file. The user posts the request at /my/download/uri/<File ID>. I want the authorisation request to be posted at auth_service:9999/files/<File ID>. The relevant part of my config is as follows:

location /my/download/uri {
    auth_request /auth/files/$uri;
    alias /my/file/directory;
}
location /auth {
    internal;
    proxy_pass http://auth_service:9999/;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
}

The request is received by the authorisation service, but at literally /files/$uri; the variable is not placed. I have tried getting the URI ready via a set variable first, but to no avail. How can I get nginx to properly direct the authorisation request?

(Note: I am aware I can include the original request in the header of the authorisation request via X-Original-URI. However, this would mean I have to do additional processing of the full URI on the authorisation server to get the relevant data, which I would rather not do if there is a way to post the authorisation request to the correct URI in the first place.)

2

There are 2 best solutions below

1
On

You cant use variables in auth_request this is apparently a design choice for nginx https://trac.nginx.org/nginx/ticket/761 I came up with this through trial and error. I had trouble putting $uri in a variable, not sure why.

location ~ /my/download/uri/(.*) {
    set $key $1
    auth_request /auth;
    alias /my/file/directory;
}
location /auth {
    internal;
    proxy_pass http://auth_service:9999/$key;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
}
1
On

I use this way and it works for my case

location = /auth {
    internal;
    proxy_pass http://auth-server$request_uri;
}