下载jwt 配置jwt
pnpm i egg-jwt
plugin.js
/** @type Egg.EggPlugin */
module.exports = {
jwt:{
enable:true,
package:'egg-jwt'
}
};
config.default.js
config.jwt = {
secret:"hakurei77" //密钥
}
创建中间层
app -> middleware
//检查token
module.exports = (options) => {
return async function jwtErr(ctx, next) {
const token = ctx.request.header.authorization;
let decode = '';
if (token) {
try {
// 解码token
decode = ctx.app.jwt.verify(token, options.secret);
await next();
console.log('decode======>',decode);
} catch (error) {
ctx.status = 401;
ctx.body = {
message: error.message,
};
return;
}
} else {
ctx.status = 401;
ctx.body = {
message: '没有token',
};
return;
}
};
}
Controller层
async ...() {
const { ctx , app } = this;
const result = await
this.ctx.service.userService....(this.ctx.request.body ,app);
ctx.body = result
}
Service层
。。。
const token = app.jwt.sign({
UserName: user.UserName,
Password: user.Password
},app.config.jwt.secret,{expiresIn:"15s"}) //里面放持续时间
result = {
"code": 200,
"msg": "成功",
"data": {
"TOKEN": token
}
}
路由层
module.exports = app => {
const { router, controller,middleware } = app;
const jwtErr = middleware.jwtErr(app.config.jwt)
router.post("/main" ,jwtErr ,controller.userController.abc)
};
标签:const,ctx,app,jwt,js,decode,token,egg
From: https://blog.csdn.net/m0_53785610/article/details/136975877