ruby-on-railsformscsrfruby-on-rails-6authenticity-token

rails 6 token authentication still needed?


I take courses on rails 5.x.x and when they used form they add a line for token authentication to protect their site, on the start of the form, like this :

<input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>">

But to be on the last version of rails i'm on 6.1.3 version and i don't see anything on the web about that. So the question is : Did I still need to set this authenticity token anywhere ? if yes, where ? and if no, why ? If you have some links about that for rails 6 I don't say no. Thank's you.


Solution

  • No, you don't need to add it manually, Rails does it for you in each form.

    <%= form_with do |form| %>
      Form contents
    <% end %>
    

    generates

    <form accept-charset="UTF-8" action="/" method="post">
      <input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" />
      Form contents
    </form>
    

    You'll notice that the HTML contains an input element with type hidden. This input is important, because non-GET forms cannot be successfully submitted without it. The hidden input element with the name authenticity_token is a security feature of Rails called cross-site request forgery protection, and form helpers generate it for every non-GET form (provided that this security feature is enabled). You can read more about this in the Securing Rails Applications guide.

    https://guides.rubyonrails.org/form_helpers.html