安装
$ mkdir egg-example && cd egg-example
$ npm init egg --type=simple
$ npm i
$ npm i egg-jwt --save
$ npm
引用egg-jwt
// config/plugin.js
module.exports = {
jwt: {
enable: true,
package: 'egg-jwt',
},
};
// config/config.default.js
/* CODE */
config.jwt = {
secret: '123456',
};
/* CODE */
配置路由
// app/router.js
module.exports = app => {
const { router, controller, jwt } = app;
router.get('/', jwt, controller.home.index); // 验证token进行访问
router.get('/login', controller.login.index); // 生成token
};
配置控制器
// app/controller/login.js
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
const { ctx, app } = this;
ctx.body = app.jwt.sign({ pwd: '123456', name: 'Lee' }, app.config.jwt.secret, {
expiresIn: '10s',
});
}
}
module.exports = HomeController;
// app/controller/home.js
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
const { ctx } = this;
ctx.body = ctx.state;
}
}
module.exports = HomeController;
访问
获取token GET http://127.0.0.1:7001/login
未超时
访问 GET http://127.0.0.1:7001/
超时
访问 GET http://127.0.0.1:7001/