Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 ActionController::InvalidAuthenticityToken error

I have a rails application which I am planning to upgrade to rails 5. I am using devise(v4.2.0) along with rails(v5.0.0). As suggested in devise README.md file, I tried moving the protect_from_forgery above the before_filter but still when I am trying to login or update my bug I get an error ActionController::InvalidAuthenticityToken

My Application Controller is

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 

And my other BugController is

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 
like image 454
H D Avatar asked Jul 12 '16 14:07

H D


People also ask

What causes Actioncontroller :: Invalidauthenticitytoken?

We get this error when the controller detects that we have not properly passed a CSRF (Cross Site Request Forgery) token in with a POST , PUT , PATCH , or DELETE request.

How do I fix invalid authenticity token?

This error can be due to corrupted cookie in your browser. Clear your browsers cache and cookies, restart the browser and try to log in.

What is Authenticity_token?

The authenticity token is designed so that you know your form is being submitted from your website. It is generated from the machine on which it runs with a unique identifier that only your machine can know, thus helping prevent cross-site request forgery attacks.


1 Answers

As indicated in Devise documentation notes for Rails 5

For Rails 5, note that protect_from_forgery is no longer prepended to the before_action chain, so if you have set authenticate_user before protect_from_forgery, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or use protect_from_forgery prepend: true.

like image 125
Alon Burg Avatar answered Sep 29 '22 04:09

Alon Burg