繁体   English   中英

Rails 5 ActionController :: InvalidAuthenticityToken错误

[英]Rails 5 ActionController::InvalidAuthenticityToken error

我有一个rails应用程序,我打算升级到rails 5.我正在使用devise(v4.2.0)和rails(v5.0.0)。 正如在设计README.md文件中所建议的那样,我尝试将proceed_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

我的另一个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

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

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

注意 :虽然这个答案具有预期效果,但它通过降低整体安全性来实现。 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

像这样

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

我使用过这样的东西,对我有用。

class WelcomeController < ActionController::Base
    protect_from_forgery with: :exception
    before_action :authenticate_model!
end

这个决定帮助了我。 我[从这里] [1]做出了决定。 就像我一样,该主题的不幸名称,使用错误的关键字我没有到达那里,所以我将在这个线程中给出,因为这里是错误的确切名称。 在我的情况下,我将以下行“添加”到application_controller.rb文件中:

protect_from_forgery with:: null_session

有一个解决方案,它说“REPLACE”行protect_from_forgery with:: exception ,如果它存在,我上面引用的那个

[1]: Rails 4真实性令牌

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM