網址:
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'] }
.