什么是JWTJSON Web Token (JWT)
- is an open standard (RFC 7519)
- that defines a compact and self-contained way
- for securely transmitting information between parties
- as a JSON object
JWT的结构JWT = Payload + Header + Signature
PayloadPayload = base64_encode(JSON Content)
vim payload.jsvar content = { "sub": "3252", "name": "Test", "iat": 1528516800, "exp": 1528603200};var buffer = new Buffer(JSON.stringify(content));var payload = buffer.toString('base64');console.log(payload);node payload.jseyJzdWIiOiIzMjUyIiwibmFtZSI6IlRlc3QiLCJpYXQiOjE1Mjg1MTY4MDAsImV4cCI6MTUyODYwMzIwMH0=HeaderHeader = base64_encode(JSON Content)
vim header.jsvar content = { "typ": "JWT", "alg": "HS256"};var buffer = new Buffer(JSON.stringify(content));var header = buffer.toString('base64');console.log(header);node header.jseyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9Signaturevim signature.jsvar payload = new Buffer(JSON.stringify({ "sub": "3252", "name": "Test", "iat": 1528516800, "exp": 1528603200})).toString('base64');var header = new Buffer(JSON.stringify({ "typ": "JWT", "alg": "HS256"})).toString('base64');var algo = require('jwa')("HS256");var secret = 'mystar';var signature = algo.sign(header + '.' + payload, secret);console.log(signature);var jwt = header + '.' + payload + '.' + signature;console.log(jwt);cnpm i --save jwanode signature.js-C46PmPVQZt8hCEy0RQ8bmB0jzwXOx4FHw7Yqx8WA7weyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzMjUyIiwibmFtZSI6IlRlc3QiLCJpYXQiOjE1Mjg1MTY4MDAsImV4cCI6MTUyODYwMzIwMH0=.-C46PmPVQZt8hCEy0RQ8bmB0jzwXOx4FHw7Yqx8WA7wHS256 = HMAC (哈希安全消息验证码) + SH256 (安全哈希算法) 更多参考 web安全 之 存储密码 & PHP开发 之 摘要和签名
JWT与SessionJWT安全基于服务器签名+HTTPS- JWT信息经过base64编码很容易解码 所以信息不会加密 只能通过签名防篡改
- JWT信息并不会加密 所以必须使用HTTPS来加密通信过程 否则信息会完全泄露
JWT存储在客户端而Session存储在服务器- JWT存储在客户端 可以缓解服务器Session存储压力
- JWT存储在客户端 便于水平扩展实现单点登录(SSO)等 但是 Session可以通过Redis等共享解决类似问题
- JWT存储在客户端 且包含有效期 所以服务器难于控制数据过期
JWT的应用场景JWT可以防止CSRF攻击关于CSRF攻击 更多参考 Web安全 之 CSRF攻击 & Laravel框架 之 CSRF
JWT可以应用于签名场景生成重置密码url审批人身份验证JWT可以应用于简单鉴权关于JWT鉴权 更多参考 JWT vs OAuth authentication & OAuth 2和JWT - 如何设计安全的API?
参考
|
|