Search code examples
javasecuritysessioncsrf

Let the csrf token expire in the user session after 15 minutes or remove it directly?


Today i've added crsf protection in my webapplication.

  • When a html for is printed i generated random token and put it in a hidden field and in user session.
  • When form is submitted i read hidden form field and compare it with token in user session.
  • If tokens match form submission may continue. If it fails a error is displayed.

To implement this i used a implementation found on the web. This implementation did not remove the token from the session once the form was submitted. I decided to remove the token from the session once the form was submitted, because it was no longer needed.

The thing i bump in to now is when i submit a form and then i press the back button of my browser and submit the form again the error appears (because token was removed from user session, but browser still holds the old form in the browser cache and displays it with the old token).

To prevent this from happening i thought of removing the token from the user session after 15 minutes. This way he should be able to go back and resubmit form. I was wondering if this is a valid and secure solution for the problem?


Solution

  • Beside preventing CSRF, the token helps you preventing double form submits too. I doubt your application is happy when a user submits the same form twice. So it's fine to remove the token on first submit and on second submit display a message saying: "The form submit is invalid or was already processed ..."