0
点赞
收藏
分享

微信扫一扫

Egg.js(二):egg-jwt验证token鉴权访问


安装

$ 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​

Egg.js(二):egg-jwt验证token鉴权访问_配置控制

​未超时​​​访问 ​​GET http://127.0.0.1:7001/​

Egg.js(二):egg-jwt验证token鉴权访问_egg_02

​超时​​​访问 ​​GET http://127.0.0.1:7001/​

Egg.js(二):egg-jwt验证token鉴权访问_jwt_03


举报

相关推荐

0 条评论