I have a website running with react on the frontend and express server with a MongoDB database on the backend. I have my authentication and session management set up as follows:
- User enters log in information, request is sent to backend
- Backend validates information and generates a unique session id
- session id is stored in database along with the user’s ID
- an httponly secure cookie is sent back to the user containing only the session id
- future requests are authenticated when the previously mentioned cookie is sent in the request, checked against the database, then the user’s Id is attached to the request so the server can fetch the user’s data
- user logs out and a delete request is sent to the server, session is deleted from the database and response contains a empty cookie to invalidate the cookie in the user’s browser
Now, this is working great for when a user checks that they want to be kept logged in. I currently have the session in the database and the cookie sent to the user set to expire after 7 days.
However, my problem is when the user doesn’t check that they want to stay logged in. In this scenario I send back a session cookie (no expiration). And it is properly wiped when the browser is closed and the user has to re-authenticate when they access the site again. However, what about the session information stored in the database? I can’t set an expiration on the document in the DB because theoretically someone could keep their browser open indefinitely and the session would need to remain valid server side that entire time. Unlike when logging out there’s no “notification” sent to the server when the user closes their browser. So, as of right now the session information in the database from when a user doesn’t want to stay logged in just kind of sits and accumulates in the database.
Any way to address this? Or should a different authentication approach be used for non-persistent sessions? Or is my whole authentication approach flawed.