我熟悉 Web 存储 API 和 cookie,但我不知道存储身份验证令牌的最安全方式是什么.我想知道这是否会破坏任何第三方库.
I'm familiar with Web Storage APIs and cookies but I can't figure what is the most secure way to store an authentication token. I'm wondering if this might break any third-party libraries.
我想要一份详尽的可用方法列表,其中包括每种方法的优缺点以及最重要的最佳方法(如果有的话).
I'd like to have an exhaustive list of available methods to do so, with the pros and cons of each and the best way above all, if any.
使用基于令牌的身份验证,您可以选择存储 JWT 的位置.我们强烈建议您将令牌存储在本地存储/会话存储或 cookie 中.
With token-based authentication, you are given the choice of where to store the JWT. We strongly recommend that you store your tokens in local storage/session storage or a cookie.
通常,JWT 放置在浏览器本地存储中,这适用于大多数用例.
Commonly, the JWT is placed in the browsers local storage and this works well for most use cases.
使用用户名和密码登录用户时,响应正文包含 access_token JWT
.然后你需要在客户端代码中处理这个响应.然后可以将此令牌存储在 localStorage 或 sessionStorage 中.
When logging in a user with a username and password, the response body contains the access_token JWT
. Then you need to handle this response in the client side code. This token can then be stored in localStorage or sessionStorage.
点击此处查看使用示例会话存储
localStorage
和 sessionStorage
都扩展了 Storage
.它们之间的唯一区别是数据的持久性:
Both localStorage
and sessionStorage
both extend Storage
. The only difference between them is the persistance of the data:
localStorage
- 数据一直存在,直到被明确删除.所做的更改已保存,可供所有当前和将来访问该网站的用户使用.
localStorage
- data persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
sessionStorage
- 所做的更改被保存并可用于当前页面,以及将来在同一窗口中访问该站点.一旦窗口关闭,存储就被删除了.
sessionStorage
- Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted.
您还可以使用 cookie 来存储 JWT.设置 cookie 的确切方式取决于您使用的客户端语言.
You can also use cookies to store the JWT. The exact way to set a cookie depends on the client side language you are using.
有不同的选项可以控制 cookie 的生命周期:
There are different options to control the lifetime of a cookie:
httpOnly
标志,则 JavaScript 和服务器端代码都可以读取 Cookie,或者只有服务器端可以读取.httpOnly
flag is set.Referer
和 Origin
标头来部分阻止.Referer
and Origin
header.原文:https://auth0.com/docs/security/store-tokens#how-to-implement
这篇关于在基于 Web 的应用程序中,在哪里正确、安全地存储 JWT 令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!