本文介绍了JWT应该存储在localStorage还是cookie中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据一些资料(例如指南和此),则JWT可以存储在 localStorage Cookies 中.根据我的理解:

For the purpose of securing REST API using JWT, according to some materials (like this guide and this question), the JWT can be stored in either localStorage or Cookies. Based on my understanding:

因此,基于上述前提-如果我们将JWT存储在Cookies中,那将是最好的选择.在对服务器的每个请求中,都将从Bear cookie中读取JWT,并使用Bearer方案将其添加到Authorization标头中.然后,服务器可以验证请求标头中的JWT(与从Cookie中读取JWT相反).

So based on the above premise - it will be best if we store JWT in Cookies. On every request to server, the JWT will be read from Cookies and added in the Authorization header using Bearer scheme. The server can then verify the JWT in the request header (as opposed to reading it from the cookies).

我的理解正确吗?如果是这样,上述方法是否涉及安全性?还是实际上我们可以先放弃使用localStorage?

Is my understanding correct? If so, does the above approach have any security concern? Or actually we can just get away with using localStorage in the first place?

推荐答案

我喜欢@ pkid169所说的文章中提到的XSRF Double Submit Cookies方法,但是有一件事情没有告诉您.您仍然没有受到XSS的保护,因为攻击者可以执行的操作是注入脚本,该脚本读取CSRF cookie(不是HttpOnly),然后使用此CSRF令牌向您的API端点之一发出请求,并自动发送JWT cookie.

I like the XSRF Double Submit Cookies method which mentioned in the article that @pkid169 said, but there is one thing that article doesn't tell you. You are still not protected against XSS because what the attacker can do is inject script that reads your CSRF cookie (which is not HttpOnly) and then make a request to one of your API endpoints using this CSRF token with JWT cookie being sent automatically.

因此,实际上您仍然容易受到XSS的攻击,只是攻击者无法窃取您的JWT令牌供以后使用,但攻击者仍可以使用XSS代表您的用户发出请求.

So in reality you are still susceptible to XSS, it's just that attacker can't steal you JWT token for later use, but he can still make requests on your users behalf using XSS.

无论是将JWT存储在localStorage中,还是将XSRF令牌存储在非仅基于HTTP的cookie中,XSS都可以轻松地捕获这两者.甚至您的HttpOnly Cookie中的JWT都可以通过高级XSS攻击来抢占.

因此,除了双提交Cookie"方法外,您还必须始终遵循针对XSS的最佳做法,包括转义内容.这意味着删除所有可能导致浏览器执行您不​​希望执行的操作的可执行代码.通常,这意味着要删除//<![CDATA [标签和HTML属性,这些属性会导致对JavaScript进行评估.

So in addition of the Double Submit Cookies method, you must always follow best practices against XSS including escaping contents. This means removing any executable code that would cause the browser to do something you don’t want it to. Typically this means removing // <![CDATA[ tags and HTML attributes that cause JavaScript to be evaluated.

这篇关于JWT应该存储在localStorage还是cookie中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!