简体   繁体   中英

Django Rest Framework + React - token vs session authentication

Although there are many posts about this topic (or closely related) on SO, I did not find what I am looking for.

As the title suggests I am using Django Rest Framework as a backend, and React as a frontend.

Now I implemented token authentication, and it works perfeclty. The only problem is that the token is stored in React's state, and if the user refreshes the page, he is no longer logged in (the token is lost).

So, now I want to switch to session authentication, since the problem is solved then. But that will require me to do some research, and before I go there I'd like to know if that is the best choice.

My question:

Do I need to use session authentication to have users stay logged in, even when the React's state changes. Or can I also achieve the same thing with token authentication (in a safe and responsible way?)

I figure I can save the token in a cookie, but that doesn't seem safe to me.

EDIT:

Later I realized, why not just store the token in a session?

SessionAuthentication would be the most straightforward way to achieve what you want. The configuration is described at http://www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme This will set a session id in a cookie that is handled by the browser.

Alternatively you can store a token in the browser's cookie but that is vulnerable to XSS attacks and other javascript attacks. For more security you can store the token in an HttpOnly cookie. The cookie would be persisted across tab/window closes by the browser.

Also to clarify cookie handling is built into most browsers. Your react state is in userland and lives in a different memoryspace than cookie storage.

More info:

  1. Ask HN: Cookies vs. JWT vs. OAuth
  2. https://developer.okta.com/blog/2017/08/17/why-jwts-suck-as-session-tokens
  3. http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM