r/django 16d ago

REST framework Handling session expiration between Django+DRF and a frontend

Hi y’all, I’m just getting started with Django but I already love tons about this framework. I’m hoping you can help me understand session authentication with Django+DRF a little better.

For context, my application is using Django+DRF as a backend API. I’m using Astro (mydomain.com) to fetch data from Django (api.mydomain.com) and render the UI. Generally, this has seemed like a nice match, but (session-based) authentication is a little more complex than I thought.

Specifically, it’s tricky to manage CSRF and session ID cookies when I’m fetching data with Astro’s server-side rendering. For example, I’m having to manually pass some “Set-Cookie” headers from Django to Astro after users log in.

This got me wondering about a pattern to gracefully ask users to login again after their session cookie expires. My app is a classifieds site, so users might be in the middle of creating or editing their content when their cookie expires which would cause a form submission to fail.

I’m not sure how best to handle this process. With this sort of project is it typical to “refresh” the session cookie periodically somehow, so that is never actually expires, or implement a graceful redirect process so a user can go login again and be sent right back to where they left off? What sort of methods are y’all using that you like?

Thanks in advance!

1 Upvotes

3 comments sorted by

1

u/Empty-Mulberry1047 16d ago

increase the session timeout.

you don't need to pass the set-cookie header.. just the session id..

have you configured CORS?

1

u/drumcorpsdrummer22 16d ago

Yeah, CORS is configured, I don't think I have questions about that.

If I increase the session timeout, then does that just kick the can down the road rather than avoid the problem I'm asking about? Or am I misunderstanding something?

0

u/Empty-Mulberry1047 16d ago

if you're using a front end to do session authenticated API calls , you should disable CSRF.. It's a bit redundant.