egg学习笔记(4)--安全机制csrf

ゝ一世哀愁。 2022-03-01 15:56 372阅读 0赞

简介

CSRF 攻击:伪造用户请求向网站发起恶意请求。

目录结构

clipboard.png

controller

//controller/postsafe.js

  1. 'use strict';
  2. const Controller = require('egg').Controller;
  3. class PostsafeController extends Controller {
  4. async index() {
  5. await this.ctx.render('postsafe')
  6. }
  7. async post(){
  8. let bodydata = this.ctx.request.body;
  9. console.log(bodydata)
  10. }
  11. }
  12. module.exports = PostsafeController;

router

//router.js

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

middleware

//middleware/auth.js

  1. module.exports = (options,app) => {
  2. return async function auth(ctx,next){
  3. ctx.state.csrf = ctx.csrf;
  4. await next()
  5. }
  6. }

//config/config.default.js

  1. config.middleware = ['printdate','forbidip','auth'];

view

//view/postsafe.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <form action="/postsafe?_csrf=<%= csrf %>" method="POST">
  11. <!-- <input type="hidden" name="_csrf" value="<%= csrf %>"> -->
  12. <div>
  13. <span>用户名</span>
  14. <input type="text" name="username">
  15. </div>
  16. <div>
  17. <span>密码</span>
  18. <input type="password" name="password">
  19. </div>
  20. <button type="submit">提交</button>
  21. </form>
  22. </body>
  23. </html>

页面效果

clipboard.png

clipboard.png

clipboard.png

去掉csrf

clipboard.png

发表评论

表情:
评论列表 (有 0 条评论,372人围观)

还没有评论,来说两句吧...

相关阅读

    相关 web安全——CSRF攻击

    > CSRF(Cross—Site Request Forgery)跨站点请求伪造,主要是利用浏览器端未过期的cookie信息伪造身份通过服务器的身份验证。 一、示例