0

I understand that CSRF protection gives some assurance that the request originated from your own web app. However, I am passing a variable from JS to Rails within the same app using:

app/views/statistics/select.js
$.ajax({
  method: "POST",
  url: "statistics/plot",
  dataType: "script",
    data: {  
    country_id: 7 
  }
});

routes:

post '/statistics/plot(:country_id)' => 'statistics#plot'

Controller:

class StatisticsController < ApplicationController
  def plot
    @selected_countries = params[:country_id]

    respond_to do |format|
      format.html{ redirect_to root_path }
      format.js
      format.json { render json: @selected_countries }
    end
  end
end

Returned:

Started POST "/statistics/plot" for ......... 
Started GET "/" for ........
Processing by StatisticsController#plot as JS
  Parameters: {"country_id"=>"7"}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)

Any ideas on what I might be doing wrong that is making the app take the post as if it is coming from an external app or API? I have searched for related posts but most involve how to disable CSRF when getting data from an API or authenticating API requests with an API key. In my case I am sending data within the same app.

amo
  • 3,030
  • 4
  • 25
  • 42

1 Answers1

0

WARNING: Can't verify CSRF token authenticity rails looks like it solves your issue:

You should do this:

Make sure that you have <%= csrf_meta_tag %> in your layout

Add beforeSend to all the ajax request to set the header like below:

$.ajax({ url: 'YOUR URL HERE',
  type: 'POST',
  beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
  data: 'someData=' + someData,
  success: function(response) {
    $('#someDiv').html(response);
  }
});
Community
  • 1
  • 1
Mark
  • 6,112
  • 4
  • 21
  • 46
  • Adding `beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},` solved the issue. – amo Mar 06 '19 at 17:38