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等。几乎不可能在您的网站中不包含任何第三方库。