Rails authenticity_token in form vs csrf token

On the same page of rails 4 application i have

in the head:

<meta name="csrf-param" content="authenticity_token" /> <meta name="csrf-token" content="some_token" /> 

and lower in the body:

 <form action="/someaction" method="post"> <input name="utf8" type="hidden" value="&#x2713;" /> <input type="hidden" name="_method" value="patch" /> <input type="hidden" name="authenticity_token" value="another_token" /> 

The csrf icon is required for js calls. But why is the shape marker different from the csrf token? Which of the two tokens is used when submitting the form?

+8
ruby-on-rails csrf authenticity-token
source share
1 answer

I did some research to answer your question, and here are the results.

First of all, consider this part:

 <meta name="csrf-param" content="authenticity_token" /> <meta name="csrf-token" content="some_token" /> 

This part is created by the csrf_meta_tags method. From the source code it can be seen that:

  • The "content" value of the <meta name="csrf-param" /> attribute is taken from request_forgery_protection_token , and the default is :authenticity_token .

  • The "content" value of the <meta name="csrf-token" /> attribute is taken from the form_authenticity_token method, where the token is either taken from the session or generated.

Now consider this part:

 <input type="hidden" name="authenticity_token" value="another_token" /> 

The source shows that:

So, if you did not manually set authenticity_token param to options in your user token and did not meet the conditions that cause the token value to be set to false (to be specified below), the token_tag method will receive nil and call the same form_authenticity_token method that is used to create tag <meta name="csrf-token" /> . By the way, to fill in the name input attribute, it also uses request_forgery_protection_token , which is used when generating the <meta name="csrf-param" /> .

And since this all happens during the same request, a call to the form_authenticity_token method should return the same result in both cases.

Which of the two tokens is used when submitting the form?

When submitting a form, a token from hidden input will be used.

A token from <meta /> can also be used, but only if all the conditions are lower (which make the token token_tag argument false):

  • :remote => true should be passed to options from form_tag .
  • embed_authenticity_token_in_remote_forms config is set to false.
  • authenticity_token not passed in options .

But why is the shape marker different from the csrf token?

Regarding this issue, perhaps this issue is due to caching. Or, perhaps, if you use the Turbolinks gem, this can cause this problem (you can check this if you completely refresh the page and compare the tokens again). For more information about the issue with Turbolinks, check out this question .

0
source share

All Articles