网址:
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>
注:配置 域白名单,跳过 crsf 检测
config/config.default.js
// 安全配置
config.security = {
csrf: {
enable: false,
ignoreJSON: true
},
// 允许访问接口的白名单
domainWhiteList: ['*'] // ['http://localhost:8080']
}
.