自己动手实现jwt(JSON Web Tokens)
发布于 7 年前 作者 fuxingZhang 4240 次预览 最后一次回复是 7 年前 来自 分享
自己动手实现JSON Web Tokens
源码:
https://github.com/fuxingZhang/jwt
原理:
https://jwt.io/
API
jwt.sign(body[, secret])
Get the token
parameters:
- body {Object} The data to be encrypted
- [secret] {String} The operation secret, default: ‘zfx’
Success will return:
- res {Object} response info, including
- status {token} token
example:
// Sign with default algorithm HMAC SHA256
const token = jwt.sign({
username: 'zfx',
role: 'admin' // get from database by captcha and password
}, 'zfx');
console.log(token)
jwt.verify(body[, secret])
verify the token
parameters:
- body {Object} The body gets from token
- [secret] {String} The operation secret, default: ‘zfx’
Success will return:
- res {Boolean} pass or not
example:
const pass = jwt.verify({
username: 'zfx',
role: 'admin',
signature: 'xxx'
}, 'zfx');
console.log(pass)
以koa为框架做测试
run server
node ./test/app
get token with method post(put data in body)
getUserInfo(put token in header)
测试截图
4 回复
为什么不用现有的包呢?
@zy445566 就是写着玩呢,之前没听说过这个,上周在论坛第一次看到,就想着自己写个玩
个人习惯:
不知道是好是坏
不要为了造轮子而造轮子…
@oyosc 😸