LocalStorage与Cookies:关于在前端安全存储JWT令牌的所有知识

We went over how OAuth 2.0 works in the last post which covered how to generate access tokens and refresh tokens. What’s next is how do you store them securely in your front-end?

我们在上一篇文章中介绍了OAuth 2.0的工作方式 ,该文章介绍了如何生成访问令牌和刷新令牌。 接下来是如何将它们安全地存储在前端中?

关于访问令牌和刷新令牌的回顾 (A Recap about Access Token & Refresh Token)

Access tokens are usually short-lived JWT Tokens, signed by your server, and is included in every HTTP request to your server to authorize the request.

访问令牌通常是短暂的JWT令牌,由您的服务器签名,并且包含在对服务器进行授权的每个HTTP请求中。

Refresh tokens are usually long-lived opaque strings stored in your database, used to get a new access token when it expires.

刷新令牌通常是存储在数据库中的长期不透明字符串,用于在过期时获取新的访问令牌。

我应该在前端将令牌存储在哪里? (Where should I store my tokens in the front end?)

There are 2 common ways to store your tokens: in localStorage or cookies. There a lot of debate on which one is better, and most people lean toward cookies for being more secure.

有两种常见的方式来存储令牌:在localStorage或cookie中。 关于哪种更好,存在很多争论,大多数人倾向于使用cookie以提高安全性。

Let’s go over the comparison between localStorage and cookies, mainly based on this post Please Stop Using Local Storage and the comments about the post.

让我们看一下localStorage和cookie之间的比较,主要基于这篇文章, 请停止使用Local Storage和对该帖子的评论。

本地存储 (Local Storage)

Pros: It’s convenient.

优点:方便。

  • It’s pure JavaScript and convenient. If you don’t have a backend, and you’re relying on a third-party API, you can’t always ask them to set a specific cookie for your site.

    它是纯JavaScript且方便。 如果您没有后端,并且依赖第三方API,则不能总是要求他们为您的网站设置特定的Cookie。
  • Works with APIs that require you to put your access token on the header like this Authorization Bearer ${access_token}.

    与要求您将访问令牌放在标头(如此Authorization Bearer ${access_token}上的API一起使用。

Cons: It’s vulnerable to XSS attacks.

缺点:它容易受到XSS攻击。

An XSS attack happens when an attacker can run JavaScript on your website. This means that the attacker can just take the access token that you stored in your localStorage.

当攻击者可以在您的网站上运行JavaScript时,就会发生XSS攻击。 这意味着攻击者只能获取您存储在localStorage的访问令牌。

An XSS attack can happen from a third-party JavaScript code included in your website, like React, Vue, jQuery, Google Analytics, etc. It’s almost impossible not to include any third-party library in your site.

XSS攻击可能来自网站中包含的第三方JavaScript代码,例如React,Vue,jQuery,Google Analytics等。几乎不可能在您的网站中不包含任何第三方库。

饼干 (Cookies

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值