how to generate AuthenticityToken on rails

2020-03-01 02:30发布

问题:

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

回答1:

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>


回答2:

This answer is first for rails form token tag in Google so to keep it simpler for future googling generations: just use token_tag, it's a helper defined in ActionView::Helpers::UrlHelper that returns hidden input with form_authenticity_token as default value.



回答3:

To generate the token you have to use the method: form_authenticity_token as it was correctly noted by @flitzwald. Since it is rediced in a active controller's concern, you must include the module into a controller expclicitly before using as follows:

include ActionController::RequestForgeryProtection

# use

def set_csrf_header
  response.headers['X-CSRF-Token'] = form_authenticity_token
end


回答4:

This is what I did and it worked:

  <form action="/users/sign_in" method="post" accept-charset="UTF-8" class="login-form new_user" id="new_user">
    <input name="utf8" type="hidden" value="&#x2713;" />
    <input name="authenticity_token" value="<%= form_authenticity_token %>" type="hidden">
    <label for="user_email">
        <span>Email:</span>
        <input autofocus="autofocus" type="email" name="user[email]" id="user_email" required />
    </label>
    <label for="user_remember_me">
        <span>Password:</span>
        <input autocomplete="off" type="password" name="user[password]" id="user_password" required />
    </label>
    <a href="#" class="forgot-password-link">Forgot your password?</a>
    <button type="submit" class="btn btn-primary submit">Log In</button>
</form>