node.js cxrf攻击

index.js代码

const express = require("express");
const app = express();
const path = require("node:path");
const session = require("express-session");
const FileStore = require("session-file-store")(session);
const uuid = require("uuid").v4;

app.set("view engine", "ejs");
app.set("views", path.resolve(__dirname, "views"));
app.use(express.static(path.resolve(__dirname, "public")));
app.use(express.urlencoded({ extended: true }));
app.use(
  session({
    store: new FileStore({
      // path用来指定session本地文件的路径
      path: path.resolve(__dirname, "./session"),
      // 加密
      secret: "哈哈",
      // session的有效时间 单位秒 默认3600s 是最大的闲置时间
      ttl: 10,
      // 默认情况下,fileStore每隔一小时删除一次session对象
      // reapInterval用来指定清除session的间隔,单位秒,默认一小时
      reapInterval: 10,
    }),
    secret: "dazhaxie",
  })
);
/* 
  cxrf攻击
    - 跨站请求伪造
    - 现在大部分的浏览器都不会在跨域的情况下发送cookie
      这个设计就是为了避免csrf攻击
    - 如何解决?
      1.使用referer头来检查请求的来源
      2.使用验证码
      3.尽量使用post请求,结合token
    - token(令牌)
      - 可以在创建表单时随机生成一个令牌,然后将令牌存储到session中,并通过ejs(模板)发送给用户,用户提交表单时,必须将token发回才可进行后续操作(可以使用uuid来生成token)
      uuid需要安装
*/
// 使路由生效
// 给路径加前缀防止路由路径重复
app.use("/students", require("./routes/student"));

app.get("/", (req, res) => {
  res.render("login");
});

app.get("/logout", (req, res) => {
  // 使session失效
  req.session.destroy(() => {
    res.redirect("/");
  });
});

app.post("/login", (req, res) => {
  // 获取用户的用户名与密码
  const { username, password } = req.body;
  if (username === "admin" && password === "123123") {
    // 登录成功后将用户信息放入session中
    // 这里仅仅是将loginUser添加到了内存当中session中,而没有将值写入到文件中
    req.session.loginUser = username;
    // 为了使得session可以立刻存储,需要手动调用save
    req.session.save(() => {
      res.redirect("/students/list");
    });
  } else {
    res.send("用户名或密码错误");
  }
});

// 404
app.use((req, res) => {
  res.status(404).send("<h1>您访问的页面已被外星人截走了</h1>");
});

app.listen(3000, () => {
  console.log("服务器已启动");
});

students.js代码

const express = require("express");
const router = express.Router();
let STUDENT_ARR = require("../data/students.json");
const fs = require("fs/promises");
const path = require("node:path");
const uuid = require("uuid").v4;

// 权限验证
router.use((req, res, next) => {
  // 方案一
  // 获取一个请求头referer
  const referer = req.get("referer");
  if (!referer || !referer.startsWith("http://localhost:3000")) {
    res.status(403).send("你没有这个权限");
    return;
  }
  if (req.session.loginUser) {
    next();
  } else {
    res.redirect("/");
  }
});

// 学生列表的路由
router.get("/list", (req, res) => {
  // 生成一个token
  const token = uuid();
  // 将token添加到session中
  req.session.token = token;
  req.session.save(() => {
    res.render("students", { stus: STUDENT_ARR, username: req.session.loginUser, token });
  });
});

// 添加学生的路由
router.post("/add", (req, res, next) => {
  // 客户端发送的token
  const token = req.body._csrf;
  const sessionToken = req.session.token;
  req.session.token = null;
  // 将客户端的token和session中的token进行比较
  if (sessionToken === token) {
    // 生成id
    const id = STUDENT_ARR.at(-1) ? STUDENT_ARR.at(-1).id + 1 : 1;
    // 1.获取用户填写的信息
    const newUser = {
      id,
      name: req.body.name,
      age: +req.body.age,
      gender: req.body.gender,
      address: req.body.address,
    };
    // 2.验证用户信息(略)
    // 3.将用户信息添加到数组中
    STUDENT_ARR.push(newUser);
    req.session.save(() => {
      // 4.返回响应
      // 调用next交由后续路由继续处理
      next();
    });
  } else {
    res.status(403).send("token错误");
  }
});

// 删除学生的路由
router.get("/delete", (req, res, next) => {
  // 获取要删除的学生id
  const id = +req.query.id;
  // 根据id删除学生
  STUDENT_ARR = STUDENT_ARR.filter(stu => stu.id !== id);
  // 将新的数组写入到文件中
  next();
});

// 修改学生的路由
router.post("/update-student", (req, res, next) => {
  // 获取学生id
  // const id = +req.query.id;// 通过查询字符串获取id
  const { id, name, age, gender, address } = req.body;
  // 修改学生信息
  // 根据学生id来获取学生对象
  const student = STUDENT_ARR.find(item => item.id === +id);
  student.name = name;
  student.age = +age;
  student.gender = gender;
  student.address = address;
  // 将新的数组写入到文件中
  next();
});

router.get("/to-update", (req, res) => {
  const id = +req.query.id;
  // 获取要修改的学生的信息
  const student = STUDENT_ARR.find(item => item.id === id);
  res.render("update", { student });
});

// 将新的数据写入到json文件中
// 处理存储文件的中间件
router.use((req, res) => {
  fs.writeFile(path.resolve(__dirname, "../data/students.json"), JSON.stringify(STUDENT_ARR))
    .then(() => {
      // res.redirect() 用来发起请求的重定向
      // 重定向的作用是告诉浏览器你向另外一个地址再发起一次请求
      res.redirect("/students/list");
    })
    .catch(() => {
      // 处理异常
      res.send("操作失败!");
      console.log("出错了---");
    });
});
module.exports = router;

students.ejs代码 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>这是学生模板</title>
    <style>
      table {
        border-collapse: collapse;
      }
      th,
      td {
        border: 1px solid #000;
        font-size: 20px;
        padding: 10px;
        text-align: center;
      }
      caption {
        font-size: 25px;
        font-weight: bold;
      }
    </style>
  </head>
  <body>
    <% for(const stu of stus){ %> <%=stu.name %> - <%=stu.age %> - <%=stu.gender %> - <%=stu.address %>
    <br />
    <% } %>
    <hr />

    <h2>当前用户:<%=username%></h2>
    <a href="/logout">登出</a>
    <% if (stus && stus.length > 0) { %>
    <table>
      <caption>
        学生列表
      </caption>
      <thead>
        <tr>
          <th>学号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>地址</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <% for(const stu of stus){ %>
        <tr>
          <td><%=stu.id %></td>
          <td><%=stu.name %></td>
          <td><%=stu.age %></td>
          <td><%=stu.gender %></td>
          <td><%=stu.address %></td>
          <td>
            <a onclick="return confirm('确认删除吗?')" href="/students/delete?id=<%=stu.id%>">删除</a>
            <a href="/students/to-update?id=<%=stu.id%>">修改</a>
          </td>
        </tr>
        <br />
        <% } %>
      </tbody>
    </table>
    <% }else{ %>
    <p>学生列表为空!</p>
    <% } %>

    <form action="/students/add" method="post">
      <!-- 直接传入请求体 -->
      <!-- hidden是一个隐藏的表单项,可以通过它传递一些不希望被用户看见的数据 -->
      <input type="hidden" name="id" value="<%=student.id%>" />
      <input type="hidden" name="_csrf" value="<%=token %> " />
      <div>
        姓名:
        <input type="text" name="name" />
      </div>
      <div>
        年龄:
        <input type="number" max="150" min="0" name="age" />
      </div>
      <div>
        性别:
        <input type="radio" name="gender" value="男" />男 <input type="radio" name="gender" value="女" />女
      </div>
      <div>
        地址:
        <input type="text" name="address" />
      </div>
      <div>
        <button>添加</button>
      </div>
    </form>
  </body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值