My Rails app features a public-facing form that passes user input to the controller as a stringified JSON via AJAX. The form is designed for offline use, and so every visit to the form page other than the first is served from the browser cache (using the cache manifest). I am having an issue where the form submission returns a 422 unprocessable entity
error unless the browser history has been cleared before navigating to the form page... that is to say that a user can only make one form submission, all subsequent submissions are 422
unless they clear the history and return to the form to refresh the cache. Unfortunately, that's not going to fly.
I am not tremendously experienced with Rails security, but I am under the impression that this has to do with CSRF protection and the fact that, for any visit to the form page other than the first, a stale CSRF token is being passed.
My AJAX request appears like so:
$.ajax({
url: "post/submission",
type: "POST",
dataType: "json",
beforeSend: function(xhr) {xhr.setRequestHeader("X-CSRF-Token", $("meta[name='csrf-token']").attr("content"))},
data: {"post" : postParameter},
success: function(response){
window.location = '/post/approval';
}
});
At the moment, the layout page includes the <%= csrf_meta_tags %>
, and I have the standard protect_from_forgery with: :exception
in the application controller.
The final structural element to note about this form is that, although the form itself is public-facing, it requires a user login after the submit button is clicked - so a submission will not be successful without a valid login.
Is there a safe way that I can get around this problem? I'm sure it goes without saying, but I can't have my users clearing their history and re-caching the form after every submission.