i use django rest framework and react js environment for my project, to store jwt token local-storage, cookie is unsafe so i decided to save httponly cookie, how do i achieve authenticate
how pass token in http header
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:
Here is my opinion.
localStorage
can be read. That's true. If we have token set in the cookies with httpOnly
setting then in the case of XSS they can not be read. Also true. Does it mean that cookies with httpOnly
are better than localStorage
? Can't say that.dangerouslySetInnerHTML
.token
from localStorage
but 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).localStorage
and cookies
.httpOnly
are used, malicious requests can be done from other sources (the Cross-Site Request Forgery). Such attack doesn't apply in the case of localStorage
.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!).