Removing header from cached response with NGINX

我怕爱的太早我们不能终老 提交于 2019-12-21 05:13:22

问题


I have NGINX running as a reverse proxy in front of a few Flask apps.

I want to implement caching for logged out users.

Flask-login adds a Set-Cookie header for every response, even for anonymous users, as it contains a session cookie with a CSRF token. This means that that I'm using proxy_ignore_headers Set-Cookie; to ensure that stuff actually get's cached by NGINX (which won't cache and response with a Set-Cookie header).

I'm setting a separate cookie in the apps to indicate the logged in/out status of a user and using that to determine whether to use the cache or not. This works great.

The issue is that the cached responses for a logged out user include the Set-Cookie header which sets the session cookie. This session cookie is served to any request that hits the cache, which ultimately results in different users receiving the same CSRF token.

I would like to either prevent the Set-Cookie header being stored in the cache, or remove/overwrite it when it's sent to the client from the cache.

I've tried setting proxy_hide_headers Set-Cookie which removes it from cached responses, but also from responses from that app. So no one can log in. Which is bad.

It feels like there should be a really easy solution to this, I just can find it no matter how hard I google.

Any help is appreciated.


回答1:


Update: After trying a million things I have a solution that’s working for multiple cookies, I would like your opinions.
On Debian 10 I installed apt-get install libnginx-mod-http-lua I think this is not the complete OpenResty lua-nginx-module, isn’t it?

map $upstream_bytes_received $hide_cookie {
   default '';
   '' Set-Cookie;
}

Inside location:

header_filter_by_lua_block {
   ngx.header[ngx.var.hide_cookie] = nil;
}

And it works, I will do more testing...


Previous answer, for 1 cookie, without Lua:

I've been working on a solution for this, but for now it works for ONLY ONE cookie.

First I faced the following problems: $proxy_hide_header does not accept variables, and cannot be used inside if().
I finally found an answer that contained a viable solution to that: Using a Header to Filter Proxied Response Headers.

So this is my code for now , that I will test more, because is a delicate matter:

map $upstream_bytes_received $cookies {
default $upstream_http_set_cookie;
'' '';
}

And then inside location:

    proxy_hide_header Set-Cookie;
    add_header Set-Cookie $cookies;

Maybe I would make the default: No cookies, that will be noticeable if fails, and less problematic regarding privacy.

But this solution I think cannot be improved for multiple cookies, I have to look elsewhere, if I could force the use of variables at $proxy_hide_header would be the end solution.



来源:https://stackoverflow.com/questions/46470330/removing-header-from-cached-response-with-nginx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!