I'm trying to prevent CSRF attacks in a an existing large web app. I've opted for a token that is injected using JS into any form and a Java Servlet filter that will check for its presence before allowing the request to continue. Firstly we are happy to require the user has JS.
Secondly - how do I do it?
The simplest idea: $(document).live("submit", myTokenAddFn);
doesn't work.
The token injection part is proving very tricky since, as I said, the web app is very large, and there a number of bridges to cross:
I feel I am very close but I can't believe I'm not impacting performance on slower browsers. I am starting to think that there might be a better way.
What I have done:
$("input[type='submit'],input[type='image'],button,a[onclick]").live("mousedown", myTokenAddFn);
The above line copes with a lot and the 'myTokenAddFn' actually just loops through the page again looking for all forms that don't have the jQuery data item I added on page load.
It copes with JSF forms that are submitted with an anchor tag's onclick attribute, buttons that don't reside in a form but submit a form and ensures that the token is always added before any other onclick handler submits the form (that might be present).The latest issue:
A JS form is dynamically added to the page and the user submits it using the enter key while the cursor is in an input text field. The user (thanks to my Java Servlet) is logged out.
The easiest fix would be to include keypress listeners to all input elements, but the performance hit here worries me.
Any suggestions? Ideas for a fresh start?
Thanks in advance.
In your simple idea, you're binding the event to document
, but I'd bind the live listener to "form"
- selecting all form tags. Also, in the event listener, just add e.preventDefault()
. Like so:
$("form").live("submit", submitListener);
function submitListener(e) {
// your handling stuff goes here
e.preventDefault();
}
I've done the above method on my forms before and it seems to work fine. Hope this does the trick!
EDIT: I just wanted to be sure this actually works, so here's a quick example. As you can see, it blocks the submission to google.com and flashes up with a "nope!" to show the submission was blocked.