使用Nginx输出CSRF(form_authenticity_token) Mixlr大量使用页面缓存,由此引入的一个问题是如何给每个页面输出会话级别的CSRF token。我们通过Nginx的子请求,从upstream web server 获取token,然后利用Nginx的SSI(server-side include)功能输出到页面中。这样既解决了CSRF攻击问题,也保证了cache能被正常利用。
location /csrf_token_endpoint {
internal;
include /opt/nginx/conf/proxy.conf;
proxy_pass "http://upstream";}
location @dynamic {
ssi on;
set $csrf_token '';
rewrite_by_lua '
-- Using a subrequest, we our upstream servers forthe CSRF token forthis session:
local csrf_capture = ngx.location.capture("/csrf_token_endpoint");
ifcsrf_capture.status == 200 then
ngx.var.csrf_token = csrf_capture.body;
-- ifthis is a newsession, ensure it sticks by passing through the newsession_id
-- to both the subsequent upstream request, and the response:
ifnot ngx.var.cookie_session then
local match = ngx.re.match(csrf_capture.header["Set-Cookie"], "session=([a-zA-Z0-9_+=/+]+);");
我们的模版文件示例: <meta name="csrf-param" value="authenticity_token"/> <meta name="csrf-token" value="<!--# echo var="csrf_token" default="" encoding="none" -->"/> Again you could make use of lua_shared_dict to store in memory the CSRF token for a particular session. This minimises the number of trips made to /csrf_token_endpoint. 原文链接:http://devblog.mixlr.com/2012/09/01/nginx-lua/