gonzo8874
gonzo8874

Reputation: 111

Confused about Django REST authentication, JWT and HTTP cookies

So after researching the best practices of authentication/security, it seems like storing the JWTs created by the backend in the localStorage is not secure, and thus, HTTP Cookies should be used, kind of. The problem is, that the simpleJWT package does not do cookies. Did not find any other up to date packages, which can deal with this task. So what should i do? Ditch the JWTs and use DRF's built-in Session Authentication?

Upvotes: 3

Views: 293

Answers (1)

pplonski
pplonski

Reputation: 5859

  • There is a misunderstanding that httpOnly cookies prevent the XSS attack. It is not true. In the case of the XSS successful attack, the hacker can use httpOnly cookies to perform malicious requests.
  • In the case of localStorage and XSS attack the hacker can directly read the auth tokens, and use them for malicious requests.
  • So malicious requests can be done for both types: localStorage and cookies httpOnly.
  • What is more, if cookies with httpOnly are used, malicious requests can be done from other sources (the Cross-Site Request Forgery (CSRF)). Such an attack doesn't apply in the case of the localStorage.

The comparison of localStorage vs cookies is from my article: React Token-Based Authentication to Django REST API Backend.

The issue to add cookies httpOnly is open in simplejwt repo: link to issue.

If you can use DRF session-based, you should use it. It is a battle-tested solution. If you want to use token-based auth, you can store the token in localStorage and it will be secure as it can be.

Upvotes: 2

Related Questions