koa里使用jwt
1.安装jsonwebtoken
npm install jsonwebtoken
2.获取token,sign.js
先不加身份验证了,只是简单生成一个token
const jwt = require('jsonwebtoken'); async function getToken(ctx) { ctx.response.type = 'json'; ctx.status = 200; const secret = 'ABCDEFG'; const token = jwt.sign({ data: 'XYZ', }, secret, { expiresIn: 60 // 过期时间 }); ctx.cookies.set( 'token', token, { domain: 'localhost', // 设置 cookie 的域 path: '/', // 设置 cookie 的路径 maxAge: 60 * 1000, // cookie 的有效时间 ms httpOnly: true, // 是否要设置 httpOnly overwrite: true // 是否要覆盖已有的 cookie 设置 } ) ctx.body = { success: true, token: `Bearer ${token}`, }; } module.exports = { 'getToken': getToken, }
3.验证token, verify.js
const jwt = require('jsonwebtoken'); const verifyToken = async (ctx, next) => { let flag = false; const secret = 'ABCDEFG'; try { let url = ctx.request.url.split('?')[0] // 检测接口是否在不校验接口列表中 let url_config = [ '/api/getToken' ] let checkUrl = url_config.some((item) => { return item == url }) if (checkUrl) { await next() } else { let token = ctx.request.headers["authorization"] token = token.replace('Bearer ', '') if (token) { let playload = await jwt.verify(token, secret) const { data } = playload; if (data === 'XYZ') { await next() } } else { ctx.body = { code: 1000, msg: '登录信息已过期' } } } } catch (error) { if (error.name == 'TokenExpiredError') { ctx.body = { code: 401, msg: 'token已过期' } } else if (error.name == 'JsonWebTokenError') { ctx.body = { code: 401, msg: '无效的token' } } else { ctx.body = { "error": { "type": "FAILED", "message": "未知", } } } } } module.exports = { 'verifyToken': verifyToken, }
4.路由 router.js
const Router = require('koa-router') const router = new Router({ prefix: '/api', // 统一前缀,接口全部为 /api/xxx 格式 }) const { verifyToken } = require('./verify') router.use(verifyToken) const sign = require('./sign'); Object.keys(sign).forEach(key => { router.all("/" + key, sign[key]); }) const test = require('./test'); Object.keys(test).forEach(key => { router.all("/" + key, test[key]); }) module.exports = router;
5.测试test.js
async function getNews(ctx) { ctx.response.type = 'json'; ctx.status = 200; ctx.body = JSON.stringify({ success: true, content: [{ id: "1", title: "news1", content: "new11111111" }, { id: "2", title: "news2", content: "new222222" }, { id: "3", title: "news3", content: "new333333" }, ], }); } module.exports = { 'getNews': getNews, }
6.入口app.js
const koa = require('koa') const app = new koa() const router = require('./router'); app.use(router.routes()).use(router.allowedMethods()) // 启动服务 let port = process.env.PORT || 3005 app.listen(port, () => { console.log(`server runing at ${port}...`) })
运行node app.js
使用postman请求
先获取token
再在headers里添加 Authorization,把上一个请求获取的token加上,就可以获取数据了