githubgit
cnpm install jsonwebtoken --save
複製代碼
config\config.default.jsgithub
config.jwt = {
secret: '我是密鑰',
};
複製代碼
userId
存儲jwtapp\controller\home.jsweb
async jwt() {
const { ctx } = this;
const userId = '123456';
const result = await ctx.service.jwt.signJwt(userId);
const data = await ctx.service.jwt.verifyJwt(result);
ctx.body = data;
}
複製代碼
async signJwt(userId) {
const { ctx } = this;
const token = jwt.sign({ userId }, this.config.jwt.secret, {
expiresIn: 60,
});
return token;
}
複製代碼
async verifyJwt(token) {
const { ctx } = this;
try {
let hasToken = false;
const userId = jwt.verify(token, this.config.jwt.secret).userId;
console.log(userId);
if (userId == '123456') {
hasToken = true;
return hasToken;
}
return hasToken;
} catch (err) {
throw (err);
}
}
複製代碼