Search code examples
ruby-on-railsruby-on-rails-3csrf

Will having two CSRF tokens on one page cause problems?


We have some pages in our Rails 3 app that generate two sets of CSRF tokens: One using csrf_meta_tag in the page headers, and one in an automatically generated form. Our ERB looks like this:

Layout:

<html>
  <head>
    <%= csrf_meta_tag %> <%# Generates CSRF tokens %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

View:

<% form_for @my_model do |f| %> <%# Generates more CSRF tokens %>
  <%= f.submit %>
<% end %>

Is this acceptable? Is there any possibility that it will cause issues when the form is submitted, whether by the generated submit button or via JavaScript? If this is a bad idea, what's the Rails way to handle this situation?


Solution

  • I don't think using two CSRF tokens will cause any problems, as long as the matching of these tokens on server side is done properly. In fact, there are some real web applications that do use two random tokens. One is present in the URL and another one is embedded in webpage. However, only one CSRF token is enough to prevent CSRF attack.