Rails 5 ActionController :: InvalidAuthenticityToken错误

我有一个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 

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

像这样

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

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

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

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

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