CSRF 攻擊:僞造用戶請求向網站發起惡意請求。html
//controller/postsafe.jsapp
'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.jsasync
router.get('/postsafe', controller.postsafe.index); router.post('/postsafe', controller.postsafe.post);
//middleware/auth.jspost
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/postsafe.htmlui
<!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>
去掉csrfthis