项目架构:vue+node.js
jwt 验证流程
1、客户端访问登陆接口(不带token),请求服务器验证
2、服务器验证通过,通过jwt返回给客户端一个token
3、客户端请求其他接口时带上从服务器获取的token
4、服务器验证客户端的token,验证通过后,返回给客户端访问接口数据
阮一峰 JSON Web Token:
http://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html
服务端node.js
1、安装依赖
npm install jsonwebtoken –save
npm install koa-jwt –save
2、中间件请求token
app.use(async (ctx, next) => {
// let token = ctx.header.authorization;
return next().catch((err) => {
if (err.status === 404) {
ctx.status = 404;
ctx.body = {
code: 404,
msg: err.message
}
} else {
throw err;
}
})
});
3、排除不验证的请求
app.use(koajwt({ secret: secret }).unless({
// 登录接口不需要验证
path: [/^\/api\/login/]
}));
4、登陆签发token
app.use(async (ctx, next) => {
if(ctx.request.method==='POST'&&ctx.request.url==='/api/login'){
const postData = ctx.request.body.user
const {login_name,login_password}=JSON.parse(postData)
//判断账号和密码是否正确
//xxx
//登陆成功返回token
const token=sign({login_name},secret,{expiresIn:'1h'})
ctx.body=token
}else{
//继续执行api请求
await next()
}
});
/* * @Author: wuyongxian * @Date: 2019-11-04 17:52:58 * @Last Modified by: * @Last Modified time: 2019-11-04 17:53:23 */ const Koa = require('koa'); const app = new Koa(); //jwt token验证 const { sign } = require('jsonwebtoken'); const secret = 'xxx'; const koajwt = require('koa-jwt'); // 中间件对token进行验证 app.use(async (ctx, next) => { // let token = ctx.header.authorization; return next().catch((err) => { if (err.status === 404) { ctx.status = 404; ctx.body = { code: 404, msg: err.message } } else { throw err; } }) }); //排除不验证的请求 app.use(koajwt({ secret: secret }).unless({ // 登录接口不需要验证 path: [/^\/api\/login/] })); app.use(async (ctx, next) => { if(ctx.request.method==='POST'&&ctx.request.url==='/api/login'){ const postData = ctx.request.body.user const {login_name,login_password}=JSON.parse(postData) //判断账号和密码是否正确 //xxx //登陆成功返回token const token=sign({login_name},secret,{expiresIn:'1h'}) ctx.body=token }else{ //继续执行api请求 await next() } }); app.listen(3000);