3

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

NM Pennypacker
  • 6,704
  • 11
  • 36
  • 38
Akash Kinwad
  • 704
  • 2
  • 7
  • 22
  • Note that CSRF protection is only useable for "classic apps" where Rails serves the views (since the client needs to get a token from a form) and the client accepts cookies. For an API that serves JSON you'll want to disable the Rails CSRF protection. https://stackoverflow.com/questions/35181340/rails-cant-verify-csrf-token-authenticity-when-making-a-post-request – max Nov 16 '18 at 13:21

2 Answers2

0

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
0

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

Chloe
  • 25,162
  • 40
  • 190
  • 357