0
votes

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

1

1 Answers

2
votes

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.

  • 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 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.
  • 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 dangerouslySetInnerHTML.
  • If there will be XSS, then the bad actor can read 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).
  • OK, so there is still an option to do malicious requests. This can be done for both types of data storing: localStorage and cookies.
  • What is more, if cookies with 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.
  • 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!).