reactjs - JWT LocalStorage 与 Cookie

我已经阅读了很多关于在哪里存储 JWT 的文章,似乎有很多人支持本地存储与 cookie 争论的双方。

微软说this关于基于 token 的身份验证:

To send the token on subsequent requests, store the token in the browser's local storage. Don't be concerned about CSRF vulnerability if the token is stored in the browser's local storage. CSRF is a concern when the token is stored in a cookie.

虽然发帖如 this强烈提倡使用 cookie:

The biggest security offenders I see today are those of us who store JWTs (session data) in local storage. Many people don't realize that JWTs are essentially the same thing as a username/password.

我想创建一个可供 SPA 和移动应用程序访问的 API。

我的理解是 SPA 可以/应该将 cookie 用于:

new CookieOptions
{
  HttpOnly = true,
  SameSite = SameSiteMode.Strict,
  Secure = true
}

虽然移动应用会将 JWT 存储在设备上并将其添加到每个请求的授权 header 中,因为它没有 cookie 的概念。

在之前的项目中我使用了jwt-decode在我的 SPA 中解析 token 中的用户信息(例如角色)。如果我使用 HttpOnly cookie,这将如何工作,因为我无法访问 token ?

简而言之,将 JWT 存储在本地存储中是否安全,或者它应该始终是一个 cookie。如果需要 cookie,我该如何确定客户端应用程序中用户的角色等?

最佳答案

使用“js-cookie”模块设置 cookie 非常普遍。这是我如何将它与 jwt 一起使用的示例。

 setSession(authResult) {
// Set the time that the Access Token will expire at
const expiresAt = authResult.expiresIn * 1000 + new Date().getTime();
// this.accessToken = authResult.accessToken;
this.idToken = authResult.idToken;
this.expiresAt = expiresAt;
Cookies.set("user", authResult.idTokenPayload);
Cookies.set("jwt", authResult.idToken);
Cookies.set("expiresAt", expiresAt);

// navigate to the home route
}

logout() {
Cookies.remove("user");
Cookies.remove("jwt");
Cookies.remove("expiresAt");
const auth = this.auth0;

auth.logout({
  returnTo: "",
  clientId: "awdf8adsf98blahblah"
});
}

https://stackoverflow.com/questions/56447066/

相关文章:

logging - 如何为 KTOR 添加日志拦截器?

amazon-web-services - 对于不支持发件人 ID 的国家/地区,AWS SNS S

csv - 在 Java 中解析大型 CSV 文件的最快最有效的方法

c# - 如何在另一个类中获取单例实例

android - Xamarin 安卓 : Cannot resolve GoogleSignIn

spring-cloud - Spring Cloud Gateway 阻止路由发现请求

ionic-framework - LocalStorage 中设置的键值可供其他应用程序访问

python-3.x - 如何在 Visual Studio Code 中使用 activate.b

sql-server - 连接到 SharePoint 服务器的 SQL 服务器

r - 如何更改 R 包的默认库路径