自己动手实现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)
Z
为什么不用现有的包呢?
F
引用 zy445566为什么不用现有的包呢?
@zy445566 就是写着玩呢,之前没听说过这个,上周在论坛第一次看到,就想着自己写个玩
个人习惯:
- 能不使用包,尽量不使用包,比如能使用原生的promise + util.promisfy,就不使用bluebird
- 能自己实现,尽量自己实现,当然,只是相对的,比如我自己实现了promise,但我绝对不会使用自己写的
不知道是好是坏
- 也许仅仅是为了代码更精简一些,引用的更少一些,相对自己而言更可控一些
- 也许仅仅是为了自我提高一丢丢
- 也许只是癖好
O
不要为了造轮子而造轮子...
F
引用 oyosc不要为了造轮子而造轮子...
@oyosc 😸
参与回复
登录后即可参与回复。登录