nginx auth_request tricky behavior

90 Views Asked by At

When I try to use nginx's auth_request , it occurred a tricky behavior:

server {
  listen 8080;
  server_name localhost;
  charset utf-8;

  set $myk $arg_k;


  location / {
    auth_request /myauth;
    proxy_pass http://nginxcluster/;
  }

  location = /myauth {
    #internal;
    default_type 'text/plain';
    proxy_set_header X-Original-URI $request_uri;
    proxy_set_header X-Original-METHOD $request_method;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";


    set $digest "test";
    
    if ($digest != $myk){
        echo $digest;
        echo $myk;
        return 403;
    }
    return 200;
    
   }
}

I got 403 when I try to access http://127.0.0.1:8080/?k=test. But I got 200 when I try to access http://127.0.0.1:8080/myauth?k=test.

How can I understand this phenomenon?It is so strange!

1

There are 1 best solutions below

1
On

In your configuration, when you access http://127.0.0.1:8080/?k=test, the subrequest made to /myauth does not include the query parameter k=test, so $myk remains unset, and the if block in the /myauth location block fails, resulting in a 403 response, On the other hand, when you access http://127.0.0.1:8080/myauth?k=test, the if block in the /myauth location block succeeds because the query parameter k=test is part of the URL, and $myk is correctly set to "test," resulting in a 200 response. to fix it your config should be like this:

server {
     listen 8080;
     server_name localhost;
     charset utf-8;

location / {
     auth_request_set $myk $arg_k;
     auth_request /myauth;
     proxy_pass http://nginxcluster/;