My task is to write a feature in a javascript package that will be embedded in html sites for form validation. Validation will be done through API call to my server.
The question is how to transfer and validate CSRF token from JS to my Rails server.
I've tried doing this:
var token = function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))};
$.ajax({
url: 'http://localhost:3000/csrf-check',
type: 'POST',
beforeSend: token,
data: {
hey: 'hey'
},
success: function(response) {
console.log(response);
}
})
In my ValidatorController:
class ValidatorController < ApplicationController
protect_from_forgery
def csrf_check
if session[:_csrf_token]
render json: :ok
else
render json: :fail
end
end
end
How can I send CSRF token and validate it on Rails server?