egg-jwt 是一个生成token的插件
token的规则:
服务器返回的token数据基本结构是 Header.Payload.Signature, header、payload、signature三部分以'.'隔开。
例如:
1 2 3 |
|
header: 一个json对象,描述JWT的元数据
payload: 一个 JSON 对象,用来存放实际需要传递的数据
signature: 对header和payload两部分的签名,防止数据被篡改
安装:
1 2 3 |
|
导入到egg项目里:
1 2 3 4 5 6 7 8 9 10 |
|
配置:
1 2 3 4 |
|
通过 jwt 生成 token:
app/controller/user.js
// 登录
async login() {
const { ctx, app } = this;
// post请求传来的参数
const { name } = ctx.request.body;
// 判断数据库里面是否存在该用户
const user = await ctx.service.user.login(name);
if(user){
// 用户存在,生成token
const token = app.jwt.sign({
name: user.name,
}, app.config.jwt.secret);
ctx.body = {
code: 200,
message: '登录成功',
data: { id: user.id },
token
}
}
}
添加中间件,以便控制jwt
module.exports = (options, app) => {
return async function jwt(ctx, next) {
const token = ctx.request.header.authorization;
let decode = '';
if (token) {
try {
// 解码token
console.log(token);
decode = ctx.app.jwt.verify(token, options.secret);
await next();
} catch (error) {
ctx.status = 401;
ctx.body = {
code: 1006,
message: error.message == 'invalid token' ? 'token无效' : error.message
};
return;
}
} else {
ctx.status = 401;
ctx.body = {
code: 1006,
message: '没有token'
};
return;
}
};
};
配置需要鉴权(校验token)的路由
app/router.js
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
const jwt = app.middleware.jwt(app.config.jwt);
router.post('/user/register', controller.user.register);
router.post('/user/login', controller.user.login);
// 添加日志 需要鉴权
router.post('/diary/add', jwt, controller.diary.add);
};
|
|
前端页面调用方式更改:
// 新增日志
axios.post('http://127.0.0.1:7001/diary/add', fieldsValue)
.then((res) => {
const { data } = res;
if(data.code === 200){
message.success(data.message || '操作成功');
}else{
message.error(data.message || '操作失败');
}
})
.catch((err) => {
console.log(err);
})
改为
// 添加日志
let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiMTIzIiwiaWF0IjoxNTgzODM5NDk5fQ.aqKI-IN9Os0v197FMKLoJzihg7UrjgMS1s-cWWt7KSM';
axios({
method: 'post',
url: 'http://127.0.0.1:7001/diary/add',
data: fieldsValue,
headers: {
Authorization: `Bearer ${token}`
}
})
.then((res) => {
const { data } = res;
if(data.code === 200){
message.success(data.message || '操作成功');
}else{
message.error(data.message || '操作失败');
}
})
.catch((err) => {
console.log(err);
})
注:密码的md5加密及验证
引用:crypto 已存在,不需要再次安装
1 |
|
加密:password 需要加密的内容
1 |
|
封装:
app/service/user.js
1 2 3 4 |
|