DEV Community

loading...

Handle CSRF issue when upgrade Rails from 5 to 6

Nuttee
Level up in Life by treating it like MMORPG Game
・2 min read

I would like to share my knowledge on how to handle the issue regarding the authenticated token from csrf_meta_tags that are not compatible between Rails 5 and 6 versions, which causes an error something like this;

Screenshot 2564-04-09 at 13.20.27

What is csrf_meta_tags?

It's a helper method to generate meta tags "csrf-param" and "csrf-token" with the name of the cross-site request forgery protection parameter and token. It's also a view helper that embeds the authenticity token into the HTML.

As you know, Rails 6 has a different algorithm for csrf token generation and its incompatibility, and to avoid showing errors to users, we decorated csrf generate function to catch the aforementioned errors and reset the session.

As mentioned previously, csrf token generation between Rails 5 and 6 is incompatibility so what should do is as given below;

Firstly, If you found that you got the error ArgumentError with invalid base64 due to an incompatible csrf token generated in your application, then you could implement the code by using the rescue concept.

Putting in application_controller.rb

rescue_from ArgumentError do |exception|
  if request.format.html? && exception.message == "invalid base64"
    request.reset_session # reset your old existing session.
    redirect_to login_path # your login page.
  else
    raise(exception)
  end
end
Enter fullscreen mode Exit fullscreen mode

Next, How about if your application needs to handle the AJAX request, then.

rescue_from ArgumentError do |exception|
  if request.format.html? && exception.message == "invalid base64"
    request.reset_session
    redirect_to signin_path
  elsif request.xhr? && exception.message == "invalid base64"
    request.reset_session
    render js: "window.location = '#{login_path}'"
  else
    raise(exception)
  end
end
Enter fullscreen mode Exit fullscreen mode

From the above snippet code, You can also check whether the request is xhr? because the AJAX request is not a request from HTML format. So it would be best if you handled this case as well.

You can then redirect a user back to the login page again if a token that's generated from the csrf_meta_tags incompatibility.

I hope this solution may solve the special issue of csrf_meta_tags that comes from upgrade Rails 5 to 6 and prevent showing the error page from the user perspective.

Discussion (0)