Add recovery from CSRF Exceptions
xredo opened this issue · comments
Use case
Sometimes Rails fails with a CSRF Exception. If the request is not AJAX we show an ugly error. If the request is AJAX it is even worse. The application fails silently.
These errors sometimes happen (without a malicious behaviour) when the browser is using a cached page to send a form.
Solution
To prevent this, we need to implement a workaround for these 2 situations. For the Ajax one, I recommend doing this:
Inside ApplicationController
rescue_from ActionController::InvalidAuthenticityToken, with: :recover_from_csrf_ajax_error
def recover_from_csrf_ajax_error
fail ActionController::InvalidAuthenticityToken unless request.xhr?
render :refresh_window
end
and inside application/refresh_window.js
location.reload();
For the other one, maybe we want to render a flash.
In my opinion we need to discuss more if we need implement it, I think this is more a framework concern.
As suggestion, if we finally implement it, we can ask for it as "Do you want to hide CSRF Exceptions?".
But I think the most of the projects that require treat this will need a more complex and custom solution.
Agree. This will greatly depend on the application when the request is not AJAX. I will include this code in a MarsBased guide to develop Rails applications. But we won't support it in the Pathfinder gem.