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

簡介

CSRF 攻擊:僞造用戶請求向網站發起惡意請求。html

目錄結構

clipboard.png

controller

//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

//router.jsasync

router.get('/postsafe', controller.postsafe.index);
  router.post('/postsafe', controller.postsafe.post);

middleware

//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

//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>

頁面效果

clipboard.png

clipboard.png

clipboard.png

去掉csrfthis

clipboard.png

相關文章
相關標籤/搜索