Authentication nginx代理身份验证拦截

Authentication nginx代理身份验证拦截,authentication,cookies,nginx,proxy,interception,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 {

我有几项服务,它们支持一个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

这几天我一直在努力解决这个问题。。。我错过了什么


谢谢

我终于明白了。我使用auth_request_set从auth响应中读取cookie,并在对调用方的响应和对目标的后续请求中手动设置cookie

因为,我已经添加了签入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;
  }
}