When developing an interface, you need to generate a token and a verification token. egg-jwt is a very good plug-in. I will teach you how to use it below. Let’s not talk nonsense, let’s see the effect first.
start tutorial
Installation package
yarn add egg-jwt
Import jwt globally
config/plugin.js
module.exports = {
jwt: {
enable: true,
package: "egg-jwt"
}
};
Global configuration jwt
config.default.js
module.exports = appInfo => {
//...
// 全局配置jwt
config.jwt = {
secret: "12345678" // 加密秘钥
};
};
Simple use of jwt
controller/login.js
实验生成token,登录后将token返回给前端
'use strict';
const Controller = require('egg').Controller;
class LoginController extends Controller {
async index() {
const { ctx } = this;
let params = ctx.request.body;
const token = await ctx.app.jwt.sign(params, ctx.app.config.jwt.secret, { expiresIn: "24h" });
console.log('token-create: ', token);
ctx.body = {
code: 0,
token
}
}
}
module.exports = LoginController;
verify token
controller/login.js
uses jwt.verify() to check the correctness of token;
'use strict';
const Controller = require('egg').Controller;
class LoginController extends Controller {
// 验证token
async testToken() {
const { ctx } = this;
const token = ctx.request.header.token;
console.log('token==2: ', token);
try {
ctx.app.jwt.verify(token, ctx.app.jwt.secret);
ctx.body = 'token正常'
} catch (err) {
ctx.body = 'token有问题'
}
}
}
module.exports = LoginController;
Advanced - middleware processing token verification
It is too troublesome to verify in each controller, you can use middleware to verify uniformly, and mount it on the route
app/middleware/jwtVerify.js
'use strict';
// 定制白名单
const whiteList = ['/login', '/login/register'];
module.exports = () => {
return async function (ctx, next) {
if (!whiteList.some(item => item == ctx.request.url)) {//判断接口路径是否在白名单
let token = ctx.request.header.token//拿到token
// console.log('jwtm---token----: ', token);
if (token) {//如果token存在
try{
let decoded = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret)//解密token
// decoded= {name, password, iat, exp} // jwt.sign时的数据,和iat,exp
await next()
}catch(err){
ctx.body = {
code: 1,
msg: 'token不对'
}
}
} else {
ctx.body = {
code: 1,
msg: '没有token'
}
}
} else {
await next()
}
}
}
configure routing
router.js
'use strict';
module.exports = app => {
const { router, controller, middleware } = app;
router.post('/login', controller.login.index);
router.post('/login/test-token', middleware.jwtVerify(), controller.login.testToken);
};
So far, jwt generates token, and verification token is processed.
If it helps you who are researching, please give a reward of one yuan to express your encouragement, or just follow and like.