Protecting form submit with ajax: with or without csrf token
I have a form whic开发者_如何学Pythonh is protected with CSRF token. I don't know all the details of CSRF tokens but I hear they're good to have for form security. When the form is submitted too late, the form gives an error so the CSRF token appears to be working as intended.
On the other hand, when I submit the form with ajax, how can I validate the form the same way I validate a normal form? I don't think I will have a form object to validate against.
- Is there a risk with using ajax?
- When I accept an ajax call, how can I validate it the same way I validate a normal form?
- I thought to pass a key with the request (like an API key) to prove that the call is being made from my application, but how can I keep this key from the naked eyes?
Is there a risk with using ajax?
Not really any more risk than any other request to your server.
When I accept an ajax call, how can I validate it the same way I validate a normal form?
I don't know, how do you validate the form now? :)
You will probably want to share this code on the server side. Create a common method/function/whatever that processes the form, given key/value pairs. The only thing different with AJAX is how the key/value pairs are sent to the server and what the formatted response is. Isolate the validation code from these details and you can just call it from both places.
Obviously, the AJAX code should send the CSRF token too.
I thought to pass a key with the request (like an API key) to prove that the call is being made from my application, but how can I keep this key from the naked eyes?
This would be pointless. JavaScript is sent as plain text, so anyone who knows anything about JavaScript will be able to extract the key.
精彩评论