Commit 140670d8 authored by 尚斌杰's avatar 尚斌杰

增加中间件实现POST的csrf

parent d3b22d45
......@@ -10,7 +10,12 @@ const Controller = require('egg').Controller;
*/
class HomeController extends Controller {
async index() {
this.ctx.body = 'hi, egg';
// egg.js POST需要增加csrf验证 this.ctx.csrf
await this.ctx.render('home.ejs');
}
async add() {
console.log(this.ctx.request.body);
this.ctx.body = this.ctx.request.body;
}
}
......
'use strict';
module.exports = () => {
return async function auth(ctx, next) {
// 设置模板全局变量
ctx.state.csrf = ctx.csrf;
await next();
};
}
;
'use strict';
module.exports = (option, app) => {
module.exports = () => {
return async function forbidIp(ctx, next) {
const forbidip = '192.168.146.169';
console.log(ctx.request.ip);
// 遍历 some 和 forEach相似
if (ctx.request.ip === forbidip) {
ctx.status = 403;
ctx.body = '您的Ip已经被屏蔽';
......
......@@ -6,6 +6,7 @@
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.post('/add', controller.home.add);
router.get('/news', controller.news.index);
router.get('/newscontent', controller.news.content);
router.get('/newslist/:id', controller.news.newslist);
......
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>首页</title>
</head>
<body>
<form action="/add" method="POST">
<input type="hidden" name="_csrf" value="<%=csrf%>" />
用户名:<input type="text" name="username" /><br/><br/>
密 码:<input type="password" name="password" type="password" /><br/><br/>
<button type="submit">提交</button>
</form>
</body>
</html>
\ No newline at end of file
......@@ -7,7 +7,9 @@ module.exports = appInfo => {
config.keys = appInfo.name + '_1537794513145_4789';
// add your config here
config.middleware = [ 'printdate', 'forbidip' ];
config.middleware = [ 'printdate', 'forbidip', 'auth' ];
// 设置中间件参数
config.printdate = {
name: '中间件',
};
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment