SPA应该在哪里保存OAuth 2.0访问令牌? [英] Where should a SPA keep a OAuth 2.0 access token?

查看:160
本文介绍了SPA应该在哪里保存OAuth 2.0访问令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

授权代码授予流中,一旦诸如单页应用程序(SPA)之类的公共客户端获得OAuth 2.0访问令牌,SPA应该将其保存在哪里?

In a Authorization Code Grant flow, once a public client such as a Single Page Application (SPA) obtains a OAuth 2.0 access token, where should the SPA keep it?


  • 将访问令牌存储在语言环境存储或会话存储中会导致跨站点脚本(XSS)攻击,因此应避免这种情况。

  • 将访问令牌存储在非httpOnly cookie中也容易受到XSS攻击,因此也应避免。

  • 将访问令牌存储在httpOnly cookie中是

所以在技术上不可能,因为我看到的唯一安全的剩余选项是将其保留在内存中。它实际上安全吗?这是唯一安全的方法吗?

So the only secure remaining option that I see is to keep it in memory. Is it actually secure? Is it the only secure way?

推荐答案

这都是要承担的风险。

如果将其存储在Cookie中,则可能会向CSRF打开应用程序。通过将令牌存储在httponly cookie中来将XSS交换为CSRF可能是有意义的,但使用非CSonly cookie除了CSRF也容易受到XSS攻击之外,使用非httponly cookie这样做没有多大意义。

If you store it in a cookie, you potentially open up your application to CSRF. While it may make sense to exchange XSS for CSRF by storing the token in a httponly cookie, it doesn't make much sense to do so with a non-httponly cookie that besides CSRF is also vulnerable to XSS.

在许多情况下,可以将其存储在localStorage或sessionStorage中。选择该选项,您将承担XSS可以访问令牌的风险。为了减轻这种风险,您可能希望实施缓解措施,例如使用合适的工具进行静态安全扫描,定期进行渗透测试等-安全不仅是代码,还涉及如何创建该代码。有了缓解措施,您就可以决定接受残余风险。

Storing it in localStorage or sessionStorage is ok in many cases. With choosing that, you accept the risk of XSS having access to tokens. To mitigate this risk, you might want to implement mitigations, like for example static security scanning with a suitable tool, regular pentesting and so on - security is not just code, it's also processes around how you create that code. With mitigations in place, you can decide to accept the residual risk.

您还可以将令牌存储在内存中,例如我想在IIFE中,从那里比较困难读取XSS攻击。将其存储在一个普通变量中无济于事(XSS的javascript仍然可以访问),而且我不确定最新的JS可以做什么以确保从给定对象外部无法对其进行安全访问。

You can also store tokens in memory, like for example in IIFEs I guess, from where it's somewhat harder to read in an XSS attack. Storing it in a plain variable doesn't help (javascript from XSS would still have access), and I'm not entirely sure about what the latest JS can do to securely make it inaccessible from outside a given object. It's probably not possible in a way that is actually secure.

或者您可以选择其他方法。您可以将非常短暂的访问令牌存储在localStorage中,以承担XSS可以访问的风险。但是,您的IdP可以在IdP域的httponly cookie中发布刷新令牌。这样,即使访问令牌遭到破坏,它也仅在有限的时间内有效,攻击者将无法对其进行续订。在某些应用程序中这可能是有道理的,而在其他应用程序中则可能没有。

Or you can go down a different route. You can store very short-lived access tokens in localStorage, accepting the risk of XSS having access. However, your IdP can issue refresh tokens in httponly cookies for the IdP domain. This way even if an access token is compromised, it is only valid for a limited amount of time, and then the attacker will not be able to renew it. This may make sense in some applications, and probably not in others.

这篇关于SPA应该在哪里保存OAuth 2.0访问令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆