且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ReactJS和DRF:如何将JWT令牌存储在HTTPonly cookie中?

更新时间:2023-01-12 11:54:57

我想您想设置httpOnly cookie,因为它比在localStorage中设置令牌(令牌)更安全吗?

I guess that you would like to set httpOnly cookie because it will be more secure than setting token (tokens) in localStorage?

最安全的方法是仅将令牌存储在内存(状态)中,而不将其存储在cookie或localStorage中.刷新每个页面后,强制用户再次登录.银行的网站就是这样运作的.

The most secure way is to store token only in memory (state) and do not store it in cookies or localStorage. After every page refresh, force the user to login again. This is how bank's websites are working.

如果您需要将令牌存储在客户端(您不想在每次刷新后都强制登录),那么我建议您使用localStorage而不是cookie.React本身受到XSS的保护.但是,如果有XSS,那么localStorage数据当然很容易读取,但cookie(甚至httpOnly)中的数据也可以被利用(通过发送带有可用cookie的请求).localStorage和cookie都容易受到XSS的攻击,但是正如我所写的,React具有针对XSS的保护.使用localStorage也更容易实现.

If you need to store the token on the client-side (you don't want to force login after every refresh) then I would recommend localStorage instead of cookies. React itself is protected against XSS. But if there will be XSS then, of course, localStorage data is easy to read but also data in cookies (even httpOnly) can be exploited (by sending requests with available cookies). Both localStorage and cookies are vulnerable to XSS, but as I wrote React has protection against XSS. Using localStorage is also easier in implementation.

请参阅以下讨论:链接到reacjs subreddit .