1
votes

I am completing the Ruby Rails tutorial for a blog and when I try and submit a new post I am getting a ActionController::InvalidAuthenticityToken error from the browser.

I am new to Ruby Rails (hence why I am doing the tutorial) and I have been back through the examples and have looked a various other answers etc and I cannot seem to find what the problem could be? I would like to understand the problem and how to fix it as part of learning.

This is what is shown in the extracted source : def handle_unverified_request raise ActionController::InvalidAuthenticityToken end end end

This is from the Server : Parameters: {"authenticity_token"=>"MijxdOhNKeov89oetl7Xa0KWpSZoeb3WAIuX0RECyIusjfjs/B5megtnH6JFOSG1G5K7g+csApABCn31UxdYGg==", "article"=>{"title"=>"po request" , "text"=>"I want to buy some cheese"}, "commit"=>"Save Article"} HTTP Origin header (https://3000-dot-4708054-dot-devshell.appspot.com) didn't match request.base_url (https://127.0.0.1:3000) Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms | Allocations: 499) ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

And this is the .erb for a new record:

<%= form_with scope: :article, url: articles_path, local: true do |form| 
%>

   <% end %>

<%= link_to 'Back', articles_path %>
<%= form_with scope: :article, url: articles_path, local: true do |form| 
%>
  <p>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
  </p>

  <p>
    <%= form.label :text %><br>
    <%= form.text_area :text %>
  </p>

  <p>
    <%= form.submit %>
  </p>
<% end %>
1
Googling ActionController::InvalidAuthenticityToken gives this as the top result: stackoverflow.com/questions/3364492/…Mark
Following that should fix your issueMark
Thanks Mark, I was a little unsure about the answer to this one as it suggests skipping the authentication and then being a vulnerability? I may have completely got the wrong end of the stick for this but I do not want to learn bad habits and would like to understand what is generating the token and why it is invalid?Joseph Hall
That's fair - sorry I was probably a bit short in my comment - I'll write out a proper answerMark
Thanks Mark, Much appreciated :)Joseph Hall

1 Answers

0
votes

The authenticity token is used by rails to ensure that requests come from the site rails is expecting. When it generates a form, it includes the verification token for this purpose. There's a much better explanation of the history / why it's used here:

Understanding the Rails Authenticity Token

If you want to keep the checks in, then the short answer is to include

<%= form_authenticity_token %>

In any views that generate forms. This will ensure the correct token is in the form, and prevent the error from occuring