2010-11-03 12 views
27

costruisco tag form da me, quando ho posto il modulo al server mi dà un errore di InvalidAuthenticityToken, quindi voglio sapere come inserirlo nel mio in situazione



come generare AuthenticityToken su rotaie

ActionController::InvalidAuthenticityToken in CropsController#update 


ActionController::InvalidAuthenticityToken 

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

risposta

62

C'è un aiutante vista chiamata form_authenticity_token che restituisce pegno l'autenticità della sessione corrente.

Nel vostro 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

Grazie, forse un modo più Rails idiomatica sarebbe '' '<% = hidden_field_tag: authenticity_token, form_authenticity_token%> '' ' – luopio

-1

Questo è quello che ho fatto e ha funzionato:

<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

Questa risposta è prima per rotaie formano tag gettone a Google in modo da mantienilo più semplice per le future generazioni di googling: usa semplicemente token_tag, è un helper definito in ActionView::Helpers::UrlHelper che restituisce l'input nascosto con form_authenticity_token come valore predefinito.

0

Per generare il token è necessario utilizzare il metodo: form_authenticity_token come è stato correttamente rilevato da @flitzwald. Dal momento che è rediced nella preoccupazione di un controllore attiva, è necessario includere il modulo in un controller expclicitly prima di utilizzare il seguente:

include ActionController::RequestForgeryProtection 

# use 

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