2010-11-03 47 views
27

我自己建的形式標記,當我的形式發佈到服務器時,它給我一個InvalidAuthenticityToken錯誤,所以我想知道如何將它添加在自己的新形勢下



如何生成AuthenticityToken在軌道上

ActionController::InvalidAuthenticityToken in CropsController#update 


ActionController::InvalidAuthenticityToken 

Rails.root: /home/mlzboy/my/crop2 
Application Trace | Framework Trace | Full Trace 

回答

62

有一個叫form_authenticity_token視圖助手返回當前會話的真實性令牌。

在你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> 
+6

謝謝,也許更Rails的慣用方法是'''<%= hidden_​​field_tag:authenticity_token, form_authenticity_token%>'' – luopio 2015-10-06 11:34:36

-1

這是我做過什麼和它的工作:

<form action="https://stackoverflow.com/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> 
5

這個答案是首先爲軌在谷歌形成令牌標籤所以爲將來的谷歌搜索世代保持簡單:只需使用token_tag,它是在ActionView::Helpers::UrlHelper中定義的幫助器,它返回的隱藏輸入爲form_authenticity_token作爲默認值。

0

要生成令牌,您必須使用方法:form_authenticity_token,因爲它正確注意到@flitzwald。因爲它是在一個活動的控制器的關注rediced,您必須包括模塊到控制器expclicitly使用如下之前:

include ActionController::RequestForgeryProtection 

# use 

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