koa-jwt 生成token问题
我问一下 koa-jwt 是不是只能验证token,不会生成token, 还是需要jsonwebtoken来生成。 koa-jwt文档里有这句话,英语渣不太懂untitled1.png
20 回复
@mikan2000 jsonwebtoken中是这样的,但是如果我引入koa-jwt 然后使用sign就会报错untitled1.png
untitled2.png
@i5ting 英语有点渣, 看了文档 好像都在写怎么验证token,然后数据会放在ctx.state.user。 所以来问问 生成token是不是还是需要
var jwt = require('jsonwebtoken');
//然后去生成token
jwt.sing()
看他的测试代码就好了
https://github.com/haorui/koa-jwt/blob/master/test.js
it('should throw if getToken function returns invalid jwt', function(done){
var app = koa();
app.use(koajwt({secret: 'shhhhhh', getToken: function(){
var secret = 'bad';
return koajwt.sign({foo: 'bar'}, secret);
}}));
request(app.listen())
.get('/')
.expect(401)
.expect('Invalid token\n')
.end(done);
});
如果说的是 https://github.com/koajs/jwt 这个库的话 的确是只能用来验证。
登陆后生成token需要用const jwt = require(‘jsonwebtoken’); 这个库来生成token
@xumjs8623 ![2_11Q]@JZZC~}AFJ`F68RWG.png](//static.cnodejs.org/Fn_XTBsTGkwXeAuFOWfwHP-Ee5_o) 我就是用的这个主题,我这是这样
@caiya 我还是用jsonwebtoken来生成token
//jsonwebtoken在服务端生成token返回给客户端
const jwt = require('jsonwebtoken')
const token = jwt.sign({
id: user._id,
secret: user.app_secret
}, config.jwt_secret, {expiresIn: 3600})
ctx.body = {
code: 200,
message: '登录成功!',
token: token
}