如何在浏览器中存储JWT? [英] How to store JWT in browser?

查看:998
本文介绍了如何在浏览器中存储JWT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次使用JSON Web令牌(JWT).我正在使用Hydra-Express框架制作Node.js应用程序.我想使用JWT进行身份验证.根据文档,我将JSON令牌返回到前端.

I'm using JSON Web Tokens (JWT) for the first time. I'm making a Node.js app using Hydra-Express framework. I want to use JWT for authentication. As per the docs, I'm returning the JSON token to the front-end.

var tokenData = {
    username: req.body.username,
};

var result = {
    username: req.body.username,
    token: jwt.sign(tokenData, 'secret', { expiresIn: 60 * 60 })
};

res.json(result);

但是我不知道如何将此JSON令牌保存到我的浏览器标头中,这样它就不会丢失,并与标头一起再次发送到后端. 每次将请求发送到后端时,如何将其保存在浏览器存储中并将其添加到请求标头中?

But I don't know how to save this JSON token to my browser header so that it doesn't get lost and is again sent to the back-end along with the header. How to save it in my browser storage and add it to the request header each time a request is sent to the backend?

推荐答案

安全建议:

尽量简短: Cookies(仅包含http和安全标记)容易受到CSRF的攻击,而不受XSS的攻击. 本地存储中的JWT易受XSS攻击,而CSRF则不易受攻击

Trying to keep it short: cookies(http-only & secure flag) are vulnerable to CSRF but not XSS. JWT in localstorage is vulnerable to XSS but not CSRF

您能做的最好的就是最大程度地降低风险: 将JWT存储在cookie中 在本地存储中存储一个csrf_token

The best you can do is to minimize the risk: store the JWT in a cookie store a csrf_token in localstorage

要使其成为无状态,请执行以下操作: 在JWT有效负载中包含csrf_token,并检查服务器端是否从本地存储读取的JWT csrf_token和csrf_token与标头中提供的匹配.

To make it stateless: Include the csrf_token in the JWT payload and check serverside if the JWT csrf_token and the csrf_token read from localstorage and provided in the header match.

这需要攻击者通过XSS获取csrf_token(例如,您在网站中使用了受感染的第三方js库,或者未进行卫生处理) 然后他需要使用csrf_token触发一个csrf请求(例如,在网页/email中嵌入img src标签或表单)

This requires an attacker to get the csrf_token through XSS (e.g. you use a compromised 3rd party js library in your site or do not apply sanitation) And then he needs to trigger a csrf request with the csrf_token (e.g. embedded img src tag or form in a webpage /email)

这种组合使攻击者更难(但并非不可能).

This combination makes it a lot harder for an attacker (but not impossible).

它提供与使用csrf_tokens的基于常规会话的身份验证相同的安全级别,但不需要状态.

It provides the same security level as a normal session based authentication with csrf_tokens, but does not require state.

这篇关于如何在浏览器中存储JWT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆