Problem with two servlet engine cookies-based sessions in one browser
Recently we met problem with sessions in our Java web app hosted in Tomcat.
Sometimes our users share one computer and browser for working with web app. Web app uses cookies-based sessions.
Web app has page with same HTML form but with specific data for each user.
Let`s imagine that User1 passes authentications and loads this form with data specific for him. Then he make some changes and forgets to submit it leaving page opened. After this another User2 visits same page with same browser and gets form with data specific for hi开发者_开发问答m. He also makes some changes in form and submits it. What does web app get? It gets User2 data submitted by User2. All is correct. But than User1 returns to computer and submits his unsubmitted form with data specific for him. What does web app get? It gets modified data specific for User1 submitted under User2. And it is the problem we met.
Servlet engine consideres request to be again from User2. We use cookies-based sessions in order to have simple URLs without additional parameter like "jsessionid=abcdef". Because of that when User1 submits his form web app gets cookie for current User2 session.
Here is an illustration:
- User1 visits -> gets cookie1 and data1 -> leave computer
- User2 visits -> gets cookie2 and data2 -> submits data2 -> web app gets cookie2 and data2 -> data2 is from User2 - correct
- User1 returns -> submits data1 -> web app gets cookie2 and data1 -> data1 is from User2 -> wrong
Did somebody met same problems? Are there any solutions? This problem was identified in Google Chrome, but I suppose that other browsers act in the same way.
There are many ways to deal with this issue. We use following two,
In all the forms, add a hidden field with user id. When user submit the form, you can check if the session is still for the same user.
To prevent XSRF attack, we add a special ID in a hidden field associated with the session. When session is changed, we can detect it right away.
When you receive a submission of data for a particular user, check that this data is actually for the user currently in session.
So, within the session object itself you'll want to store a reference to the current logged-in user, and you'll have to have a way to tie back a form submission/the data contained in it to the user that it belongs to.
精彩评论