简体   繁体   中英

Rails Error: ActionController::InvalidAuthenticityToken

I am getting this error: ActionController::InvalidAuthenticityToken on every single post request on my webapp.

My temporary solution is adding this to the controller: skip_before_action :verify_authenticity_token but of course the creates a vulnerability...

Does any one know why I might be getting this error, so I can fix it without creating a vulnerability?

Thank you.

You need to send authenticate token with your HTTP call to controller. Normally if you are using form_for helper then you don't need to send authenticity token explicitly. But if you using HTML form <form> or Ajax request then you must send this token with you call.

Ajax

$.ajax({  
.....,  
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},  
....... });

Form put this inside html form tag

<%= tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) %> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM