自己动手实现jwt(JSON Web Tokens)
发布于 6 年前 作者 fuxingZhang 3426 次浏览 来自 分享

自己动手实现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)

post http://localhost:3000/v1/api/geToken

getUserInfo(put token in header)

get http://localhost:3000/v1/api/getUserInfo

测试截图

getToken.png

getUserInfo.png

expired.png

4 回复

为什么不用现有的包呢?

@zy445566 就是写着玩呢,之前没听说过这个,上周在论坛第一次看到,就想着自己写个玩

个人习惯:

  • 能不使用包,尽量不使用包,比如能使用原生的promise + util.promisfy,就不使用bluebird
  • 能自己实现,尽量自己实现,当然,只是相对的,比如我自己实现了promise,但我绝对不会使用自己写的

不知道是好是坏

  • 也许仅仅是为了代码更精简一些,引用的更少一些,相对自己而言更可控一些
  • 也许仅仅是为了自我提高一丢丢
  • 也许只是癖好

不要为了造轮子而造轮子…

回到顶部