I need to use a Single Page Application (React, Ember, Angular, I don\'t care) with Rails CSRF protection mechanism.
I\'m wondering if I need to create a token evey
I don’t know what exact issue you are facing. But if you are getting CSRF issues in New Rails versions and need to include Rails CSRF tokens in ajax requests you can follow the steps below.
Recently I used Rails 5.1 application.
When using ajax calls to fetch some data from APIs I was getting CSRF token issues:
‘WARNING: Can't verify CSRF token authenticity rails’
The reason was
Rails 5.1 removed support for jquery and jquery_ujs by default, and added
//= require rails-ujs in application.js
It does the following things:
But it is not including the csrf token for ajax request by default. Beware of that. We have to explicitly pass it like:
$( document ).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-Token': Rails.csrfToken()
}
});
----
----
});
Note that in Rails 5.1 version, you get ‘Rails’ class in js, and can make use of the functions.
Update: If you are using Rails server side and other front end, you really don't want to use Rails provided CSRF tokens. Because Its really not matter which backend service you are using.
If your aim is to block CSRF, you need to set up CORS in backend, that is your Rails backend. Rails is now providing a separate file in initializer for this. You can mention which sites are allowed to send ajax requests to your backend.
Edit here:
config/initializers/cors.rb
If you want authentication, use basic auth, token auth Or JWT