Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate AuthenticityToken on rails

I build the form tag by myself and when I post the form to server it give me a InvalidAuthenticityToken error, so I want to know how to add it in my own in current situation:

<form accept-charset="UTF-8" action="/crops/update" method="post">   <input id="crop_x" name="crop_x" size="30" type="text" /><br />     <input id="crop_y" name="crop_y" size="30" type="text" /><br />   <input id="crop_w" name="crop_w" size="30" type="text" /><br />    <input id="crop_h" name="crop_h" size="30" type="text" /><br />   <input id="crop" name="crop" type="submit" value="Crop!" /> </form> 

Response error is:

ActionController::InvalidAuthenticityToken in CropsController#update  ActionController::InvalidAuthenticityToken Rails.root: /home/mlzboy/my/crop2 Application Trace | Framework Trace | Full Trace 
like image 891
mlzboy Avatar asked Nov 03 '10 08:11

mlzboy


People also ask

How authenticity token works in Rails?

When the user submits the form, Rails looks for the authenticity_token , compares it to the one stored in the session, and if they match the request is allowed to continue. Since the authenticity token is stored in the session, the client cannot know its value.

What is CSRF token in rails?

Rails CSRF TokenThe server generates these tokens, links them to the user session, and stores them in the database. This token is then injected into any form presented to the client as a hidden field. When the client correctly submits the form for validation, it passes the token back to the server.


1 Answers

There is a view helper called form_authenticity_token that returns the current session's authenticity token.

In your view.html.erb:

 <form action="/blah" method="POST">    <input name="authenticity_token" value="<%= form_authenticity_token %>" type="hidden">    <input name="first_name" type="text">  </form> 
like image 189
flitzwald Avatar answered Sep 21 '22 17:09

flitzwald