2016-11-06 266 views
0

我有幾個服務,他們站在一個nginx實例後面。爲了處理認證,在nginx中,我攔截每個請求並將其發送到認證服務。在那裏,如果證書是正確的,我設置一個包含用戶相關信息的cookie。nginx代理服務器認證攔截

該請求現在應該路由到相應的服務,並設置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"; 
    } 
} 

如果我提出請求到/ AUTH-代理具有x靶標頭手動設置,響應包含按預期該cookie。

如果我向所需的目標發出請求,請求被攔截,它會到達/ auth-proxy,它正確設置cookie。但是,當請求到達目標時,它不包含cookie。

我假設nginx在執行目標請求時並未轉發cookie。

最近幾天我一直在爲此苦苦掙扎...我錯過了什麼?

謝謝!

回答

1

我終於想通了。我使用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; 
    } 
}