我目前正在使用ReactJS构建一个单页应用程序。

我读到不使用localStorage的原因之一是因为XSS漏洞。

既然React会转义所有用户输入,那么现在使用localStorage是否安全呢?


当前回答

Philippe De Ryck博士写了一篇有用的文章,深入分析了漏洞(尤其是XSS)的真正影响。

这篇文章让人大开眼界!

简而言之,开发人员最关心的应该是保护web应用程序不受XSS的影响,而不应该太担心使用哪种类型的存储区域。

菲利普医生建议采取以下3个步骤:

Don't worry too much about the storage area. Saving an access token in localStorage area will save the developer a massive amount of time for development of next phases of the application. Review your app for XSS vulnerabilities. Perform a through code review and learn how to avoid XSS within the scope of your templating framework. Build a defense-in-depth mechanism against XSS. Learn how you could further lock down your application. E.g. utilising Content Security Policy (CSP) and HTML5 sandboxing.

记住,一旦你被XSS攻击了,游戏就结束了!

其他回答

只要加密,将令牌存储在localStorage中是安全的。下面是一个压缩的代码片段,展示了许多方法中的一种。

    import SimpleCrypto from 'simple-crypto-js';

    const saveToken = (token = '') => {
          const encryptInit = new SimpleCrypto('PRIVATE_KEY_STORED_IN_ENV_FILE');
          const encryptedToken = encryptInit.encrypt(token);

          localStorage.setItem('token', encryptedToken);
     }

然后,在使用令牌之前,使用PRIVATE_KEY_STORED_IN_ENV_FILE对其进行解密

localStorage和httpOnly cookie都不能接受吗?关于一个妥协的第三方库,我所知道的唯一能减少/防止敏感信息被窃取的解决方案是强制执行子资源完整性。

子资源完整性(SRI)是一种安全特性 浏览器验证它们获取的资源(例如从CDN) 交付时没有意外的操作。它通过允许 您可以提供所获取资源必须的加密散列 匹配。

只要受感染的第三方库在您的网站上是活跃的,键盘记录程序就可以开始收集信息,如用户名,密码,以及您输入到网站的任何其他内容。

httpOnly cookie将阻止来自另一台计算机的访问,但不会阻止黑客操纵用户的计算机。

Philippe De Ryck博士写了一篇有用的文章,深入分析了漏洞(尤其是XSS)的真正影响。

这篇文章让人大开眼界!

简而言之,开发人员最关心的应该是保护web应用程序不受XSS的影响,而不应该太担心使用哪种类型的存储区域。

菲利普医生建议采取以下3个步骤:

Don't worry too much about the storage area. Saving an access token in localStorage area will save the developer a massive amount of time for development of next phases of the application. Review your app for XSS vulnerabilities. Perform a through code review and learn how to avoid XSS within the scope of your templating framework. Build a defense-in-depth mechanism against XSS. Learn how you could further lock down your application. E.g. utilising Content Security Policy (CSP) and HTML5 sandboxing.

记住,一旦你被XSS攻击了,游戏就结束了!

Localstorage被设计成可以通过javascript访问,所以它不提供任何XSS保护。正如在其他回答中提到的,有很多可能的方式来进行XSS攻击,默认情况下,本地存储不受保护。

However, cookies have security flags which protect from XSS and CSRF attacks. HttpOnly flag prevents client side javascript from accessing the cookie, Secure flag only allows the browser to transfer the cookie through ssl, and SameSite flag ensures that the cookie is sent only to the origin. Although I just checked and SameSite is currently supported only in Opera and Chrome, so to protect from CSRF it's better to use other strategies. For example, sending an encrypted token in another cookie with some public user data.

因此,cookie是存储身份验证数据的更安全的选择。

TLDR;

两者都可以工作,但是使用httpOnly cookie要比使用localStorage安全得多,因为XSS引入的任何恶意javascript代码都可以读取localStorage。