csrf_meta_tags and form_for generate invalid base64 on Heroku
On our servers this problem was caused by downgrading Rails from 6.1 to 6.0.3.
Firstly we tried to upgrade rails from 6.0.3 to 6.1, but missed some needed changes for migration to be successful and had to revert back to 6.0.3. However, during the time our app ran on Rails 6.1 many user requests were served and new csrf tokens were generated. The thing is, Rails 6.1 has different algorithm for csrf token generation and when we reverted back to Rails 6.0.3, tokens that were generated by Rails 6.1 could not be validated.
To alleviate the problem and avoid showing errors to users we decorated csrf generation function to catch aforementioned errors and reset session so that tokens compatible with Rails 6.0.3 can be generated.
def rescued_csrf_meta_tags csrf_meta_tagsrescue ArgumentError request.reset_session csrf_meta_tagsend
Additional server info:
- Ubuntu 16.04
- Ruby 2.6.5
EDIT: As @cecomp64 wrote in the comment, another solution is to clear browser cache. Obviously, this won't be easy to implement if your app has many users.
This is because the csrf token generation between Rails 5 and 6 is incompatible (different algorithm) and as such, you need a function to generate a new encryption to handle the aforementioned compatibility errors.
Your application_controller.rb:
protect_from_forgery with: :exception
Your application.html.erb in the head tag:
<%= csrf_meta_tags %>
Your application_helper.rb or csrf_helper.rb:
def csrf_meta_tags if defined?(protect_against_forgery?) && protect_against_forgery? [ tag("meta", name: "csrf-param", content: request_forgery_protection_token), tag("meta", name: "csrf-token", content: form_authenticity_token) ].join("\n").html_safe endend