javascript - 使用 Http 和 Secure 在 Cookie 中存储 Jwt token ,而不是在 Javascript 中使用 LocalStorage

标签 javascript cookies jwt

大家好,

我正在从事一个具有 Web API (RestAPI) 和 SPA(单页应用程序)解决方案的项目。

根据我在 Udemy 上关注的视频,他将 jwt token 存储在本地存储中,但后来我发现存储在本地存储中有点冒险,因为攻击者可以复制实际 token 并在未来发出请求.

我读过一些博客,认为在 cookie 中存储 token 很好,因为您可以将 cookie 设置为 httpOnly 并且安全。但问题是,我不知道如何实现它。

这是我在用户拥有有效登录名时的示例代码:

axios.post('api/login/', this.account).then(response=>{
    if(response){
        localStorage.setItem('token', response.data.token); // will successfully save to localstorage
        // navigation here
    }
}).catch(error=> console.log(error); );

如何使用安全设置将其存储在 cookie 中?

最佳答案

您不能从客户端代码(如 Javascript)设置 HttpOnly cookie。因此,不得使用 Javascript 读取此类 cookie。您必须从服务器设置此类 cookie。您可以发送带有服务器响应的 cookie,浏览器将从 header 中读取信息来存储它们。之后,浏览器会将该 cookie 发送到服务器,每次请求都会发送到服务器,直到 cookie 过期。

您可以从服务器设置 cookie,如下所示。

Cookie cookie = new Cookie(name, value); //name and value of the cookie
cookie.setMaxAge(expire); //expire could be 60 (seconds)
cookie.setHttpOnly(true);
cookie.setPath("/");
response.addCookie(cookie);

关于javascript - 使用 Http 和 Secure 在 Cookie 中存储 Jwt token ,而不是在 Javascript 中使用 LocalStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52829514/

相关文章:

javascript - 在数组中查找不连续的数字对

javascript - 响应式菜单(CSS 问题)[顶级菜单之间的空格]

javascript - HTML 文本框的动态拼写检查器?

angularjs - 错误 : [$injector:unpr] http://errors. angularjs.org/1.3.5/$injector/unpr?p0=

plugins - 如何在 Firebreath 插件中获取 NPP 实例?

php - 如何在每个页面中使 PHP cookie 全局化

ios - JWT 用于从服务器发送 iOS 推送消息

javascript - 在隐藏的溢出中隐藏零件 View 文本

java - Spring Security : Why . AuthorizeRequests().antMatchers ("/api/v1/web/**").permitAll() 不起作用?

java - JWT 验证失败 : Key bytes cannot be specified for RSA signatures. 请指定 PublicKey 或 PrivateKey 实例