nginx代理身份验证拦截

时间:2016-11-06 07:38:32

标签: authentication cookies nginx proxy interception

我有一些服务,他们支持nginx实例。为了处理身份验证,在nginx中,我拦截每个请求并将其发送到身份验证服务。在那里,如果凭据是正确的,我正在设置一个包含用户相关信息的cookie。

现在应该将请求路由到相应的服务,并设置cookie。

这是我的nginx配置:

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
  worker_connections  1024;
}

http {
  upstream xyz {
    server ***;
  }

  upstream auth {
    server ***;
  }

  server {
   listen       8080;
   location ~ ^/(abc|xyz)/api(/.*)?$ {
     auth_request /auth-proxy;

     set $query $2;

     proxy_pass http://$1/api$query$is_args$args;
     proxy_set_header X-Target $request_uri;
     proxy_set_header Host $http_host;
   }

   location = /auth-proxy {
    internal;
    proxy_pass http://auth;

    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Target $request_uri;
    proxy_set_header Host $http_host;
    proxy_set_header X-CookieName "auth";
    proxy_set_header Cookie "auth=$cookie_auth";
    proxy_set_header Set-Cookie "auth=$cookie_auth";
    proxy_cookie_path / "/; Secure; HttpOnly";
    add_header Cookie "auth=$cookie_auth";
    add_header Set-Cookie "auth=$cookie_auth";
  }
}

如果我使用手动设置的x-target标头向/ auth-proxy发出请求,则响应会按预期包含cookie。

如果我向所需目标发出请求,请求被截获,它到达/ auth-proxy,正确设置cookie。但是,当请求到达目标时,它不包含cookie。

我假设在执行目标请求时nginx没有转发cookie。

在过去的几天里,我一直在努力解决这个问题......我错过了什么?

谢谢!

1 个答案:

答案 0 :(得分:2)

我终于明白了。我使用 auth_request_set 从auth响应中读取cookie,并在响应调用者和后续请求时手动设置它。

因为if is evil,我已经在lua中添加了支票。

server {
  listen       8080;
  location ~ ^/(abc|xyz)/api(/.*)?$ {
    auth_request /auth-proxy;

    # read the cookie from the auth response
    auth_request_set $cookie $upstream_cookie_auth;
    access_by_lua_block {
      if not (ngx.var.cookie == nil or ngx.var.cookie == '') then
        ngx.header['Set-Cookie'] = "auth=" .. ngx.var.cookie .. "; Path=/"
      end
    }
    # add the cookie to the target request
    proxy_set_header Cookie "auth=$cookie";

    set $query $2;

    proxy_pass http://$1/api$query$is_args$args;
    proxy_set_header X-Target $request_uri;
    proxy_set_header Host $http_host;
  }
}