0
votes

I'm trying to implement authentication with django-rest-auth library in the backend and I'm using react for the front-end. Django-rest-auth returns a token after authentication and I was guessing how to handle it.

  • From a security perspective can that token be saved in an HTTPOnly cookie or it should be kept only in memory?

  • Exists a tested approach to achieve local persistence with django-rest-auth and react without implementing vulnerabilities in the website?

1
Hi Andrea. Are you serve your frontend code from one endpoint and then fetch dynamic data from Django rest api browserside and want on subsequent reload not to reauthorize?DmitriyBelovol
Actually, I'm serving the front-end directly in Django using the build folder. And yes, I don't want to reauthorize on subsequent reloads since it will ruin my user experienceAndreaCostanzo1
Do you realize, that your approach make it impossible to make any SEO on your site and leave it invisible for crawlers? I’m sorry for this question, I ask because I got this situation by myself ;)DmitriyBelovol
And yes, they say that it’s dangerous to persist in LocalStorage, but in almost all tutorials they does use it for token’s persistence.DmitriyBelovol
I strongly recommend you use GraphQL instead of REST. it’s amazing expirience. Particularly- FormidableURQL on the front and Django Graphene on the back. It’s absolutely amazing experience. Ways ways simpler than RESTDmitriyBelovol

1 Answers

1
votes

Every method of storing token on the client-side has some weakness:

  • storing the token in HTTPOnly cookie makes the application vulnerable to CSRF attack
  • storing the token in localStorage makes the application vulnerable to XSS attack

I'm personally using the localStorage to store token because it is convenient. React has built-in XSS prevention and you can additionally switch on CSP (Content Security Protection). I write the article about my approach: https://saasitive.com/tutorial/react-token-based-authentication-django/ - the httpOnly vs localStorage discussion is at the end of the post. There is also full tutorial how to start SaaS app with Django and React (link).