How to handle Invalid Authenticity Token json request from application controller in rails

1.2k views Asked by At

When user tries to fill form using script or automation, application controller raises error of the

"ActionController::InvalidAuthenticityToken"

This happens for valid genuine users when they fill a form, close their browser, reopens the page from their browser history and submit form.

In this case I don't want to send an exception using exception notifier, and I also want to show the modal with the refreshed request message.

So I have modified application_controller as

class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception

  rescue_from ActionController::InvalidAuthenticityToken, with: :handle_csrf_error

  def handle_csrf_error(exception)
    respond_to do |format|
      format.js {
        render 'invalid_requests/error'
      }
      format.html {
        render text: I18n.t('errors.messages.csrf_error')
      }
    end
    ExceptionNotifier.notify_exception(exception)
  end

end

I want to make this works for all types of requests.

I have added responses for the html & js requests

But not getting how to handle the json request.

P.S > json request is sent from web application for load more case & sometimes exception raises, so want I to handle this.

My Rails version is 4.2

2

There are 2 answers

0
Chloe On

Turn off the check for the authenticity token in your controller.

skip_before_action :verify_authenticity_token

See http://stackoverflow.com/questions/1177863/ddg#1177883

0
David Ramos On

After you make sure your request is correctly making a json request and not a js one (check your Content-Type header). Add a format.json to your server response.

respond_to do |format|
  format.json { render json: true }
end