The below text is from my article React and Token-based Authentications with Django REST API Backend, which is a part of complete tutorial on how to build SaaS with Django and React from scratch.
There is a lot of discussion over the internet on how to store the
auth_token in the website to be secure:
- Reddit post Local Storage vs Cookie [Authentication Tokens],
- GitHub discussion security: pulling tokens from localStorage is not secure
Here is my opinion.
- The most secure option is to not store any security data on the client-side. Just force a user to login every time she refreshes the website or opens a website in a new tab.
- In the case of XSS (Cross Site Scripting) attack the values from the
localStoragecan be read. That’s true. If we have token set in the cookies with
httpOnlysetting then in the case of XSS they can not be read. Also true. Does it mean that cookies with
httpOnlyare better than
localStorage? Can’t say that.
- First of all, React has a built-in mechanism against XSS attacks. It will render raw HTML only if you explicitly ask for it with
- If there will be XSS, then the bad actor can read
localStoragebut what can he do with it? He can send it to his server or use it for malicious requests. We can protect the application against loading unknow scripts from unknown sources with Content Security Policy (CSP) (for sure I will write about it in future posts).
- OK, so there is still an option to do malicious requests. This can be done for both types of data storing:
- What is more, if cookies with
httpOnlyare used, malicious requests can be done from other sources (the Cross-Site Request Forgery). Such attack doesn’t apply in the case of
- The easiest solution to protect agains mailicious requests is to logout (in our case). In this tutorial, at logout the token is destroyed, so it can’t be used anymore to authenticate requests (Im using Djoser package).
- To summarize, in the case of XSS, there is no rescue (cookies won’t help much). Cookies enable one more type of additional attack CSRF.
Please keep in mind that CSRF cookies are disabled in DRF if you are using token-based authentication. CSRF cookies are only enabled in the case of session-based authentication. So if you still want to use
httpOnly cookies, please remember to use CSRF cookies (otherwise CSRF attacks are possible!).
CLICK HERE to find out more related problems solutions.