understanding csrf and session expiration

Hi,

I’m writing a shopping cart application. Frequently, users visiting a product page are having their session expire, and getting a csrf error when they finally submit the form.

For example: If they visit the product page during the evening, then go to sleep and try to add the product to their cart the next morning, they get an error because the session has expired.

What confuses me is why there aren’t widespread posts about this. Sessions timeout quite frequently on most servers. Users do not always fill out the form they’re viewing in one sitting.

It doesn’t make sense in this instance to throw up a “your session is about to expire” warning, since the user is not logged in, and is just browsing. As far as they’re concerned, they haven’t created any sort of “session”.

What is the best practice here?

-Charlie

Hi,

I just thought I’d refresh this question with a follow-up.

I’m wondering if the solution here is for me to turn off csrf protection on the product pages.

There are no text input fields in the form submitted by the user. It’s just a radio button with a product id. I’m not sure why I’d need csrf protection here. Is csrf protection only needed for forms that submit text fields?

Alternatively, I could have an ajax script on a timer run right before the session expires, and get a new token, updating the _csrf field in the form… but this seems more complicated than I need.

Anyone have any thoughts on this?

-Charlie

Hi Charlie,

My thought about session is that it is there on purpose, it should be temporary and only for limited time. Although we can have session stored in the database, it is still only for temporary storage in limited time.

CSRF is there for purpose as well. It is a best practice to have it turned on to protect our app.

For your case, shopping cart, my approach is like this. If a customer not login (regardless he is registered customer or not), he or she can still add products to his or her shopping cart, he or she allow to add anything until check out stage. When, he or she want to checkout but not login, he or she should login before proceeding. However, if he or she just add a product and do nothing until session expired, it is his or her responsibility since he or she is not login. Hence, customer needs to login first to have his or her shopping cart still stays.

Another approach is to use cookies. If customer is not login, his or her shopping cart is stored in the database identified by its cookies. As customer, I never like the idea of storing cookies on my pc. It should be fine since the cookies only identifier for shopping cart stored in the database. There is no relation between the cookies and user since customer is not login yet.

Just my thought, welcome for feedback and discussion.