Egg 安全机制 CSRF 的防范

网址:

http://eggjs.org/zh-cn/core/security.html

方式一:
在 controller 中通过参数传入模板
/**
 * 方式一:在 controller 中通过参数传入模板
 * this.ctx.csrf 用户访问这个页面的时候生成一个密钥
 */
await ctx.render('home', {
  csrf: this.ctx.csrf
});
方式二:
通过创建中间件,设置模板全局变量
app/middleware/auth.js
/**
 * 同步表单的 CSRF 校验
 */
module.exports = (options, app) => {
  return async function auth(ctx, next) {
    // 设置模板全局变量
    ctx.state.csrf = ctx.csrf;

    await next();
  }
}

config/config.default.js

// 增加配置中间件
config.middleware = ['auth'];

controller 中使用

/**
 * 方式二:通过创建中间件,设置模板全局变量
 * config.middleware = [auth'];
 */
await ctx.render('home');

模板:

app/view/home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>首页</title>
</head>
<body>
    <form action="/add?_csrf=<%=csrf%>" method="POST">
        <!-- 通过隐藏的表单域传值 -->
        <!-- <input type="hidden" name="_csrf" value="<%=csrf%>" /> -->
        用户名:<input type="text" name="username" /><br />
        密  码:<input type="password" name="password" /><br />
        <button type="submit">提交</button>
    </form>
</body>
</html>

.

猜你喜欢

转载自www.cnblogs.com/crazycode2/p/12443812.html