Tuesday, January 09, 2007

Preventing Multiple Form Submits

Synchronizer Token Pattern


The Synchronizer Token Pattern is a server-side way to prevent multiple form submissions which is widely used in J2ee.





Extract from Core J2EE Patterns


Duplicate Form Submissions


Users working in a browser client environment may use the Back button and inadvertently resubmit the same form they had previously submitted, possibly invoking a duplicate transaction. Similarly, a user might click the Stop button on the browser before receiving a confirmation page, and subsequently resubmit the same form. In most cases, we want to trap and disallow these duplicate submissions, and using a controlling servlet provides a control point for addressing this problem.


Synchronizer (or Déjà vu) Token


This strategy addresses the problem of duplicate form submissions. A synchronizer token is set in a user's session and included with each form returned to the client. When that form is submitted, the synchronizer token in the form is compared to the synchronizer token in the session. The tokens should match the first time the form is submitted. If the tokens do not match, then the form submission may be disallowed and an error returned to the user. Token mismatch may occur when the user submits a form, then clicks the Back button in the browser and attempts to resubmit the same form.


On the other hand, if the two token values match, then we are confident that the flow of control is exactly as expected. At this point, the token value in the session is modified to a new value and the form submission is accepted.


You may also use this strategy to control direct browser access to certain pages, as described in the sections on resource guards. For example, assume a user bookmarks page A of an application, where page A should only be accessed from page B and C. When the user selects page A via the bookmark, the page is accessed out of order and the synchronizer token will be in an unsynchronized state, or it may not exist at all. Either way, the access can be disallowed if desired.



ASP.NET client-side solution


The common way used to prevent multiple form submissions in ASP.NET seems to be to use javascript to disable the button on the page. This is not an ideal solution, with many drawbacks, but will work in the majority of situations.


Disable button (blog)


No comments: