ruby-on-rails - Rails 5 InvalidAuthenticityToken,但 token 存在

标签 ruby-on-rails ruby-on-rails-5 csrf csrf-protection

我正在使用 ActionController::InvalidAuthenticityToken 保存一个简单的资源..

存在 CSRF 元标记:

<meta name="csrf-token" content="Z4fDRsIqCp4cvpCw1Dp6kN7z0uPNF5otp611C80YhUg/oB+AcUy+dz2b5qKyoMMo48LdEvbF3dcBn2d0GqeR+g==" />

以及表单的标记字段:

<input type="hidden" name="authenticity_token" value="bIMZ5cndd/CTgOwjC3quOp02WlvWdDmhdNQCyKb920HIZz2Y8vvNDlTa7d4PKaJ5pUY6QkHKYCqiHikc2rFsyQ==" />

session 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 %>

Controller 中相关的操作:

  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 容器作为代理,也许我的配置不正确?这是配置:

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 添加代理配置来解决此问题,如 here 所述。 :

我错过了这些:

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;

关于ruby-on-rails - Rails 5 InvalidAuthenticityToken,但 token 存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44373078/

相关文章:

ruby-on-rails - Rails 在创建时向表中添加数据

ruby-on-rails - rails : How to implement protect_from_forgery in Rails API mode

javascript - 富文本编辑,防止嵌入javascript代码

html - 有哪些 HTML 表单攻击媒介?

ruby-on-rails - 如何在 JSONAPI::Resource 中执行 `has_one: model, through: join_model`

ruby-on-rails - 我的/public 目录可以是带有 rails 3 + 乘客 3 + nginx 0.8 的符号链接(symbolic link)吗?

ruby-on-rails - 在 Ruby on Rails 上的 ActiveRecord 中获取下一条/上一条记录

ruby-on-rails - 使用货币 rails : How to manually set an attribute's currency

ruby-on-rails - 来自控制台的 ActionCable.server.broadcast

ruby-on-rails - Belongs_to 在 Rails 5 中的存在不起作用