ruby-on-rails - 使用 render_to_string 时创建的真实性 token 不同

标签 ruby-on-rails csrf ruby-on-rails-4 pusher render-to-string

我正在通过 render_to_string 生成一个小表格并且由于某种原因,CSRF token 没有正确生成(即它与 header 不同,用户在提交时注销,以及日志上的“无法验证 CSRF token ”)。这是相关的代码:

Controller :

def publish
  @question = @event.questions.find(params[:id])
  @question.update_attribute(:published, true) unless @question.published?
  Pusher[@event.to_param].trigger('new_question', question: render_question)
  redirect_to event_path(@event)
end


private
  def render_question
    render_to_string('questions/_unanswered_question', locals: {question: @question}, layout: false)
  end
  def fetch_event
    @event ||= current_user.events.find(params[:event_id])
  end

我正在使用 Pusher,但您可以假设这只是使用此 Javascript 呈现在页面上:
$("#questions").append(data.question); // data is what I send from Pusher.

最后,正在渲染的部分:
.answer
  = form_for [@event, question, question.answers.new] do |f|
    %h2
      = question.title

    %ul
      - (1..5).each do |n|
        - if question.send("answer_#{n}").present?
          %li
            = f.radio_button :option, n, id: "q_#{question.id}_answer_option_#{n}"
            = f.label question.send("answer_#{n}"), for: "q_#{question.id}_answer_option_#{n}"

    %p
      = f.submit "Answer"

这在没有附加到页面的情况下工作得很好,但在布局中呈现。请注意,这不是远程表单。

最佳答案

看起来您正在使用 ajax 生成表单,然后将其添加到 Dom。为每个请求生成新的 csrf token 。据我所知,您必须使用 header 中可用的 csrf token ,并使用 js 将表单中的 token 替换为它。

应该是这样的:

success: ()->
  parameter = $("meta[name=csrf-param]").attr("content")
  token     = $("meta[name=csrf-token]").attr("content")
  question  = $(data.question).find("[name="+parameter+"]").val(token)

目前我没有电脑可以先测试,所以希望我是对的:/

关于ruby-on-rails - 使用 render_to_string 时创建的真实性 token 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17953105/

相关文章:

ruby-on-rails - 动态属性列表 rabl

php - Laravel 具体如何构建和检查 CSRF token ?

http - 利用服务器端缓存进行 CSRF 保护

ruby-on-rails - 延迟作业 - Rails 4

ruby-on-rails-4 - 无法使用 Authlogic 路由至/注销

ruby-on-rails - 我可以使用 Twitter gem 缓存结果吗? ( rails 4)

mysql - Rails 部署 - 数据库未上传

jquery - jquery-select2 的依赖下拉内容

ruby-on-rails - 像偏执狂一样不恢复记录

spring-security - Spring Cloud Gateway POST 禁止