const Koa = require("koa"); const Router = require("koa-router"); const jwt = require("jsonwebtoken"); const jwtAuth = require("koa-jwt"); const secret = "it's a secret"; // 密钥 const app = new Koa(); const router = new Router(); router.get('/api/login',async (ctx) => { const {username,passwd} = ctx.query; if(username === "aaron" && passwd == "123456"){ const token = jwt.sign({ data:{name:"Aaron",userId:"1"}, // 用户信息 exp:Math.floor(Date.now()/1000)+60*60 // 过期时间 },secret); ctx.body = {code:200,token}; } else{ ctx.status = 401; ctx.body = {code:0,message: "用户名密码错误"}; } }); router.get("/api/userinfo",jwtAuth({secret}),async (ctx) => { // jwtAuth受保护路由 ctx.body = {code:200,data:{name:"Aaron",age:18}} }); app.use(router.routes()); app.listen(3000);
因为最后生成的token是通过base64加密的,有些内容是可以反解的,所以千万不要在数据里面添加有关数据的敏感信息。注意注意。。。