使用 http 和 Secure 将 jwt 令牌存储在 cookie 中,而不是在 javascript 中存储 lo



伙计们,美好的一天,

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

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

我读过一些博客,说在cookie中存储令牌很好,因为您可以将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。因此,此类 cookie 不应使用 Javascript 读取。您必须从服务器设置此类 Cookie。您可以发送带有服务器响应的cookie,浏览器将存储它们从标头读取的内容。之后,浏览器会将该 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);

我读过一些博客,说在 cookie 中存储令牌很好,因为 您可以将 Cookie 设置为仅限 http 且安全。但问题是,我 不知道如何实现它。

您需要在服务器上实现这一点,而不是在客户端上实现。

下面是登录端点的服务器代码示例:

// If the passwords match, generate a new jwt for this user
const token = user.generateAuthToken();
// Set the options for the cookie
let cookieOptions = {
// Delete the cookie after 90 days
expires: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000 ),
// Set the cookie's HttpOnly flag to ensure the cookie is 
// not accessible through JS, making it immune to XSS attacks  
httpOnly: true,
};
// In production, set the cookie's Secure flag 
// to ensure the cookie is only sent over HTTPS
if( process.env.NODE_ENV === 'production') {
cookieOptions.secure = true;
}
// Send a success response to the client
// including the jwt in a cookie
return res
.cookie('jwt', token, cookieOptions)
.status(200)
.json({
msg: 'Successfully logged in',
});
}

这看起来类似于: 通过 Javascript 将 cookie 设置为 HttpOnly

为了补充这个来源引用的答案:

为了防止跨站点脚本 (XSS( 攻击,HttpOnly cookie 是 无法访问 JavaScript 的 Document.cookie API

为了使用 httpOnly 和安全标志保存令牌,服务器必须在标头中对此进行响应(再次取自上述来源(:

设置饼干: id=a3fWa;到期=星期三, 21 十月 2015 07:28:00 GMT;安全; 仅 httponly

因此,我认为如果服务器没有使用 Set-Cookie 标头进行响应,而是将令牌作为响应正文返回,则无法安全地保存 cookie。

最新更新