egg学习笔记(4)--安全机制csrf
简介
CSRF 攻击:伪造用户请求向网站发起恶意请求。
目录结构
controller
//controller/postsafe.js
'use strict';
const Controller = require('egg').Controller;
class PostsafeController extends Controller {
async index() {
await this.ctx.render('postsafe')
}
async post(){
let bodydata = this.ctx.request.body;
console.log(bodydata)
}
}
module.exports = PostsafeController;
router
//router.js
router.get('/postsafe', controller.postsafe.index);
router.post('/postsafe', controller.postsafe.post);
middleware
//middleware/auth.js
module.exports = (options,app) => {
return async function auth(ctx,next){
ctx.state.csrf = ctx.csrf;
await next()
}
}
//config/config.default.js
config.middleware = ['printdate','forbidip','auth'];
view
//view/postsafe.html
<!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>Document</title>
</head>
<body>
<form action="/postsafe?_csrf=<%= csrf %>" method="POST">
<!-- <input type="hidden" name="_csrf" value="<%= csrf %>"> -->
<div>
<span>用户名</span>
<input type="text" name="username">
</div>
<div>
<span>密码</span>
<input type="password" name="password">
</div>
<button type="submit">提交</button>
</form>
</body>
</html>
页面效果
去掉csrf
还没有评论,来说两句吧...