Rails的5 InvalidAuthenticityToken,但令牌存在
问题描述:
我得到的ActionController :: InvalidAuthenticityToken保存简单的资源..Rails的5 InvalidAuthenticityToken,但令牌存在
CSRF meta标签存在:
<meta name="csrf-token" content="Z4fDRsIqCp4cvpCw1Dp6kN7z0uPNF5otp611C80YhUg/oB+AcUy+dz2b5qKyoMMo48LdEvbF3dcBn2d0GqeR+g==" />
和表单的令牌字段:
<input type="hidden" name="authenticity_token" value="bIMZ5cndd/CTgOwjC3quOp02WlvWdDmhdNQCyKb920HIZz2Y8vvNDlTa7d4PKaJ5pUY6QkHKYCqiHikc2rFsyQ==" />
会话ID不是在请求之间持续存在,但我知道这种行为是在发生CSRF错误时使用的。
形式的代码:
<%= form_for document do |f| %>
<% if document.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(document.errors.count, "error") %> prohibited this document from being saved:</h2>
<ul>
<% document.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
控制器相关的操作:
def new
@document = Document.new
end
def create
@document = Document.new(document_params)
respond_to do |format|
if @document.save
format.html { redirect_to @document, notice: 'Document was successfully created.' }
format.json { render :show, status: :created, location: @document }
else
format.html { render :new }
format.json { render json: @document.errors, status: :unprocessable_entity }
end
end
end
不知道如何甚至解决此,原因很明显,我不愿意关闭CSRF保护。
编辑:我正在通过一个nginx容器作为代理,也许我的配置是不正确的?下面是配置:如列出here
upstream backend {
server service:3000;
}
server {
listen 80 default_server;
error_page 500 502 503 504 /500.html;
error_log /dev/stdout info;
access_log /dev/stdout;
location/{
proxy_pass http://backend;
}
}
答
为别人运行到这背后的nginx的代理,这是通过将代理配置nginx的解决:
我缺少这些:
proxy_set_header X-Real_IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_set_header Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_pass_header Set-Cookie;
答
我在这个问题上挣扎了几天,直到我终于在我的nginx设置中偶然发现了这条缺失的行:
location @puma {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Forwarded-Proto https; # Needed to avoid 'WARNING: Can't verify CSRF token authenticity'
proxy_pass http://puma;
}
添加缺失的行“proxy_set_header X-Forwarded-Proto https;”后,我所有的CSRF令牌错误都会退出。
你在使用设计吗? – Gerry
不,还没有添加任何额外的宝石 – user1456632
更新我的问题与潜在的相关信息 – user1456632