自己动手实现jwt(JSON Web Tokens)
自己动手实现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)