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












1















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










share|improve this question

























  • 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. stackoverflow.com/questions/35181340/…

    – max
    Nov 16 '18 at 13:21


















1















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










share|improve this question

























  • 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. stackoverflow.com/questions/35181340/…

    – max
    Nov 16 '18 at 13:21
















1












1








1








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










share|improve this question
















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







ruby-on-rails json ajax authenticity-token






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 13:04









NM Pennypacker

4,702112531




4,702112531










asked Nov 16 '18 at 11:55









Akash KAkash K

105211




105211













  • 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. stackoverflow.com/questions/35181340/…

    – max
    Nov 16 '18 at 13:21





















  • 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. stackoverflow.com/questions/35181340/…

    – max
    Nov 16 '18 at 13:21



















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. stackoverflow.com/questions/35181340/…

– max
Nov 16 '18 at 13:21







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. stackoverflow.com/questions/35181340/…

– max
Nov 16 '18 at 13:21














2 Answers
2






active

oldest

votes


















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





share|improve this answer

































    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






    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53337404%2fhow-to-handle-invalid-authenticity-token-json-request-from-application-controlle%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      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





      share|improve this answer






























        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





        share|improve this answer




























          0












          0








          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





          share|improve this answer















          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






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 18 '18 at 22:47

























          answered Nov 18 '18 at 22:14









          DavidDavid

          12




          12

























              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






              share|improve this answer




























                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






                share|improve this answer


























                  0












                  0








                  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






                  share|improve this answer













                  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







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 18 '18 at 23:18









                  ChloeChloe

                  11k1982198




                  11k1982198






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53337404%2fhow-to-handle-invalid-authenticity-token-json-request-from-application-controlle%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Xamarin.iOS Cant Deploy on Iphone

                      Glorious Revolution

                      Dulmage-Mendelsohn matrix decomposition in Python