Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tomcat session cookie doesn't expire

I have a web application in Tomcat 7 which keeps user information in session as a DTO object. I also have Spring security enabled for my project which automatically redirects a user to a login page if the user does not have a session.

If I log in to my application once and then I restart Tomcat in Eclipse what happens is that my session gets flushed out but the cookie does not go.

What this means is that after server restart there is no UserDto in session but a valid JSESSIONID remains with browser. Thus spring security still thinks that the user is logged in when in fact he's not.

Why is this happening? (I have check the type of JSESSIONID cookie by viewing page info in Firefox it says - Expire: At end of session. Thus it should ideally expire at server restart or shouldn't it?)

Edit: Though Firefox says Expire: At end of session the cookie is still there if I close and restart Firefox.

like image 445
Kshitiz Sharma Avatar asked Jun 18 '26 09:06

Kshitiz Sharma


2 Answers

From Servlet 3.0 to add expire date to a cookie you can add cookie-config to your web.xml file

<session-config>
    <session-timeout>30</session-timeout> 
    <cookie-config>
        <max-age>1800</max-age>
    </cookie-config>
</session-config>
like image 114
Tomasz Godziński Avatar answered Jun 20 '26 21:06

Tomasz Godziński


The cookie is held in the browser - when the server restarts, but the browser continues to run, it will hold onto the cookie and present this to the server on next request.

Now on the server side, you have multiple options: You can configure tomcat's SessionManager to persist on disk and read the content upon restart - this is an option that also is used to distribute sessions between multiple tomcats in a cluster: When the session is serialized to disk, any server can continue the session by "just" deserializing it. There's some cost implied (as you constantly need to serialize sessions)

Currently I can't give you more concrete hints than this - but if you look it up and understand the difference between where the cookie is stored, why it doesn't change on server restart and that you'll have to look up tomcat documentation of the session manager, you'll hopefully manage to figure it out.

like image 41
Olaf Kock Avatar answered Jun 20 '26 23:06

Olaf Kock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!