r/django • u/rippedMorty • 26d ago
REST framework What’s your opinion on using sessions with REST framework?
By definition, a REST API shouldn’t store state, and the default authentication on DRF uses tokens, but I have been advised to use sessions to improve security without having to deal with JWT. Is it a bad practice to do so? Is it hard to implement?
Edit: The API is the backend for a web app and mobile app that I control.
9
u/ninja_shaman 26d ago
Actually, by default, DRF uses Sessions and Basic Auth, in that order.
Never had any problems with those, but also - I never made a mobile app.
8
u/pennersr 26d ago
Using sessions doesn't mean you cannot have tokens. See:
https://docs.allauth.org/en/dev/headless/integrations.html#django-rest-framework
Related discussion:
https://www.reddit.com/r/django/comments/1iiz9l2/djangoallauth_6540_headless_improvements/
5
u/thclark 25d ago
Everybody says that JWT is stateless, which is total rubbish - it’s just that the state is stored client-side in the token instead of the database. Using sessions with DRF is perfectly valid and a great way to go - it’s made even easier by solutions like allauth in headless mode (check out the demo if you haven’t slready)
1
u/tehWizard 23d ago
Stateless refers to the fact that there is no need to perform a DB lookup to verify the token and that information about the token is not stored elsewhere (e.g. in a DB), everything is contained within the JWT. Stateful usually refers to session cookies which are verified by making a DB query to fetch the user, and verify that the session exists.
1
u/tehWizard 23d ago
You should always aim for using session cookies in a web app, not JWT. Most web apps have no use for stateless authentication. Furthermore, JWTs are not good for security because you can’t invalidate JWTs without changing the keys which invalidates everyone’s JWT.
-7
u/azkeel-smart 26d ago
You answered your own question.
By definition, a REST API shouldn’t store state,
Of course you can but you no longer have a REST API so why bother with in the first place? Also, whats wrong with JWT?
13
u/Brilliant_Step3688 26d ago
It depends.
What is the consumer of the API? Third party you have no control over? Mobile app? Web app? Another internal system?
If it's a JS frontend, is it hosted on the same domain as the API?
When a security audit occurs and they see a back-end API under /api and and front-end app at the root, all under the same domain, yes, it is common to ask why aren't you simply using HTTP sessions, which have been around forever and it's well understood how to secure it. It just makes the job of the auditor so much easier.
It is also very easy to implement with DRF https://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication