首页 > 解决方案 > 带有 cookie 的 nginx auth_request

问题描述

可能是这个问题的副本,但它没有答案,我在那里尝试了这个建议,但无法让它发挥作用。我需要在代理之前授权每个请求,我试图通过 cookie 来做到这一点,但 cookie 值未在任何后续请求上设置。互联网上的大多数地方都推荐以下内容

server {
  auth_request /auth;

  location /auth {
    internal;
    proxy_pass http://auth:8080/auth;
    auth_request_set $saved_set_cookie $upstream_http_set_cookie;
    add_header Set-Cookie $saved_set_cookie;
  }
}

但这似乎不起作用。如上面的问题所述,我什至尝试使用自定义标题来查看是否可以看到它,但它不起作用。

server {
  auth_request /auth;

  location /auth {
    internal;
    proxy_pass http://auth:8080/auth;
    auth_request_set $saved_set_cookie $upstream_http_set_cookie;
    add_header X-COOKIE-TEST $saved_set_cookie;
  }
}

如果我直接访问身份验证服务器,我会看到 cookie 已设置

在此处输入图像描述

标签: authenticationnginxcookies

解决方案


https://github.com/nginxinc/NGINX-Demos/blob/331fd357e6e1813b5d41aed48880cf274d31dcee/oauth2-token-introspection-oss/frontend.conf#L29找到了一个可行的解决方案,它非常简单(Nginx 1.18.0):

  location / {
    auth_request /authz;
    auth_request_set $new_cookie $sent_http_set_cookie; # use sent_http_*, not upstream_http_*
    add_header Set-Cookie $new_cookie;
    add_header X-Test $sent_http_set_cookie;            # it's even working directly
  }

推荐阅读