Rails 5 ActionController :: InvalidAuthenticityToken错误

HSD*_*HSD 25 ruby ruby-on-rails devise ruby-on-rails-5

我有一个rails应用程序,我打算升级到rails 5.我正在使用devise(v4.2.0)和rails(v5.0.0).正如设计README.md文件中所建议的那样,我尝试将prevent_from_forgery移到before_filter之上但仍然在我尝试登录或更新我的错误时出现错误ActionController::InvalidAuthenticityToken

我的Application Controller

class ApplicationController < ActionController::Base
 protect_from_forgery with: :exception, prepend: true
 before_action :configure_permitted_parameters, if: :devise_controller?

  protected

   def configure_permitted_parameters
     devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
     devise_parameter_sanitizer.permit(:account_update, keys: [:name])
   end

end
Run Code Online (Sandbox Code Playgroud)

我的另一个BugController

class BugsController < ApplicationController
  protect_from_forgery prepend: true, with: :exception
  before_action :authenticate_user!
  before_action :set_bug, only: [:show, :edit, :update]

    def update
      respond_to do |format|
      if @bug.update(bug_params)
        format.html { redirect_to @bug, notice: 'Bug was successfully updated.' }
        format.json { render :show, status: :ok, location: @bug }
     else
        format.html { render :edit }
        format.json { render json: @bug.errors, status: :unprocessable_entity }
     end
     end
   end

private
def bug_params
  params.require(:bug).permit(:product, :component, :title, :description, :status_id, :created_by_id, :assigned_to_id)
end


end
Run Code Online (Sandbox Code Playgroud)

Alo*_*urg 73

正如Rails 5的Devise文档说明中所示

对于Rails 5,请注意链protect_from_forgery不再是前缀before_action,因此如果您authenticate_user 之前已设置protect_from_forgery,则您的请求将导致"无法验证CSRF令牌真实性".要解决此问题,请更改您调用它们的顺序,或使用protect_from_forgery prepend: true.

  • 这似乎是一种比跳过验证真品令牌更好的选择! (7认同)
  • 这应该是选择的答案 (2认同)

Bol*_*z0r 11

注意:虽然这个答案具有预期效果,但它通过降低整体安全性来实现.Alon的以下答案更为正确,并保持了网站的安全性.

class BugsController < ApplicationController
skip_before_filter :verify_authenticity_token
protect_from_forgery prepend: true, with: :exception
before_action :authenticate_user!
before_action :set_bug, only: [:show, :edit, :update]
end
Run Code Online (Sandbox Code Playgroud)

像这样

  • It is better to use skip_before_action instead of skip_before_filter... (4认同)

fuz*_*oup 5

我最近以相当大的方式遇到了这个问题,我发现我的错误是我的应用程序的域名最近更改了,但我忘记更新 session_store.rb。这可能不是每个人的问题,但它会将其报告为 CSRF 错误。所以请检查 config/session_store.rb