简体   繁体   中英

Is it safe to escape authenticity token using skip_before_filter?

Button_to produce the authenticity token in its form. However, invalid authenticity token error is raised and so many threads suggested adding of callback to the specific action in the target controller like below:

<!-- view filw -->

<%= button_to "Delete all", "", :method => :delete, :id =>  "delete_confirmation_button",:onclick => "return confirm('Are you sure you want to delete items?')",
    :params => {"#{object.class.name.downcase}_id" => object.id }, 
    :form   => {:id =>  "tool_bar_delete_form"} %>

Since the form path is decided according to selected items I use the following function to add form action later

 function detect_selected_items(object_name){

  /*  some code */

  var items_ids_string = "" ;
  switch (object_name )
  {
    case "Questionnaire":
      items_ids_string = "/questionnaire_items/" ;
      break;
    case "Lesson":
      items_ids_string = "/lesson_items/" ;
      break;
    case "Exam":
      items_ids_string = "/answers/" ;
      break;
   };

  items_ids_string += "delete_all/"
  items_ids_string += items_ids.join(",")
  document.getElementById("tool_bar_delete_form").action = items_ids_string  ;
}

<!-- controller file -->

skip_before_filter :verify_authenticity_token, :only => :delete_all

since the callback is working quite well. My question:

Is it safe to add such callback function to the controller and if not? how to prevent CSRF in such cases?

Does adding form actions through scripts cause such error?

No, you should not skip CSRF protection in this case. Do you have javascript intercepting the click on delete_confirmation_button ? I'm almost certain that you do, an unintercepted button_to would not have this problem.

If you are intercepting the click with JS and using JS to submit the form, you should update the script to include the content of the CSRF meta tag present on the page. The CSRF meta tags look like this:

<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="include-this-in-your-request" />

Add a param to your request named "authenticity_token" with the value of the csrf-token to your javascript request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM