如何使用基于koa2的koa-jwt?

基于koa2的koa-jwt和基于koa1有很大差别,前者去掉了对sign,verify和decode函数的支持。我想问一下,我现在把jwt引入了:

const jwt = require('koa-jwt');
app.use(jwt({ 
  secret: 'my-secret' 
}).unless({path: [/^\/backend\/login/]}));

但是因为没有sign函数,我在/login接口返回的时候应该怎样把token加到返回的body中?

阅读 6.8k
4 个回答

看了一下 koa-jwt@koa2 的文档,因为之前没用过,文档写得也不是很细致,看得不是很明白。大概这里有一句话,是说默认用 ctx.state.user,所以你试下呢

The JWT authentication middleware authenticates callers using a JWT token. If the token is valid, ctx.state.user (by default) will be set with the JSON object decoded to be used by later middleware for authorization and access control.

不知道你的意思是不是这样的:因为没有 sign 函数,所以不知道该怎么得出 token 。

如果你的问题确实是如上所述,那请你看看 koa2 下的 kao-jwt 文档:

jsonwebtoken — JSON Web Token signing and verification

Note that in the koa-v2 branch koa-jwt no longer exports the sign, verify and decode functions from the above module. Please use the module directly.

koa-jwt 的 sign 函数其实是从 jsonwebtoken 导出的,现在它不直接导出了,你要用的话需要直接去用 jsonwebtoken。

就是这样。

koa-jwt已经说明了自己使用的是jsonwebtoken,你把这个库引一下,自己做一下sign就好了,这样我觉得满好的

新手上路,请多包涵

我也没有看懂他让如何来验证,坐等大神的 DEMO 。。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题