I'm working on a Rails app (version 4.2.5) that uses the rack-offline gem to cache a form that users can fill out when they have no internet connection (entries are stored as localStorage objects which can be submitted later when user has connectivity). However, when the form is submitted, I am getting the error
ActionController::InvalidAuthenticityToken in EntriesController#create
This occurs when I open a new browser window while the Rails server is off and navigate to http://localhost:3000/entries/new (the page has been cached - it renders just fine), fill out the form, then turn the server back on and try to submit.
From my Entries controller:
def create
@entry = Entry.create(entry_params)
redirect_to "http://localhost:3000/entries"
end
And the Application controller:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
And the in my layout view includes <%= csrf_meta_tags %>
Are there any ways that I can get around this issue without compromising the security of the app?
EDIT In the Application controller, I replaced
protect_from_forgery with: :exception
with
protect_from_forgery with: :null_session
and this solved the problem. However, I don't know enough about what all of this means to understand whether or not this creates a security vulnerability. Does it? (PS - I really want to avoid security vulnerabilities)
The csrf_meta_tags are useful for ajax form submissions if you have javascript that's smart enough to use them. Otherwise you need to put a regular form field with the token into your form:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
This will likely fix your issue if you are in the case where you have somehow built a form without including the authenticity token.
Here are some other ideas:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With