1. 程式人生 > >egg學習筆記(4)--安全機制csrf

egg學習筆記(4)--安全機制csrf

簡介

CSRF 攻擊:偽造使用者請求向網站發起惡意請求。

目錄結構

clipboard.png

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>

頁面效果

clipboard.png

clipboard.png

clipboard.png

去掉csrf

clipboard.png