# egg-security **Repository Path**: mirrors_eggjs/egg-security ## Basic Information - **Project Name**: egg-security - **Description**: Security plugin for egg, force performance too. - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-11-23 - **Last Updated**: 2026-03-08 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # @eggjs/security [![NPM version][npm-image]][npm-url] [](https://github.com/eggjs/security/actions/workflows/nodejs.yml) [![Test coverage][codecov-image]][codecov-url] [![Known Vulnerabilities][snyk-image]][snyk-url] [![npm download][download-image]][download-url] [](https://nodejs.org/en/download/) [](https://makeapullrequest.com)  [npm-image]: https://img.shields.io/npm/v/@eggjs/security.svg?style=flat-square [npm-url]: https://npmjs.org/package/@eggjs/security [codecov-image]: https://codecov.io/gh/eggjs/security/branch/master/graph/badge.svg [codecov-url]: https://codecov.io/gh/eggjs/security [snyk-image]: https://snyk.io/test/npm/@eggjs/security/badge.svg?style=flat-square [snyk-url]: https://snyk.io/test/npm/@eggjs/security [download-image]: https://img.shields.io/npm/dm/@eggjs/security.svg?style=flat-square [download-url]: https://npmjs.org/package/@eggjs/security egg 内置的安全插件 ## 使用方式 egg 默认开启此插件,所以无需配置。 修改 `config/config.js` 文件修改配置 ```js exports.security = { xframe: { value: 'SAMEORIGIN', }, }; ``` ### 关闭安全防范 如果你想关闭其中一些安全防范,直接设置该项的 `enable` 属性为 false 即可,如关闭 xfame 防范: ```js exports.security = { xframe: { enable: false, }, }; ``` ### match 和 ignore 如果只想开启针对某一路径,则配置 match 选项,例如只针对 `/example` 开启 csp ```js exports.security = { csp: { match: '/example', // match: /^\/api/, // support regexp // match: ctx => ctx.path.startsWith('/api'), // support function // match: [ ctx => ctx.path.startsWith('/api'), /^\/foo$/, '/bar'], // support Array policy: { //... }, }, }; ``` 如果需要针对某一路径忽略某安全选项,则配置 ignore 选项,例如针对 `/example` 关闭 xframe,以便合作商户能够嵌入我们的页面: ```js exports.security = { xframe: { ignore: '/example', // ignore: /^\/api/, // support regexp // ignore: ctx => ctx.path.startsWith('/api'), // support function // ignore: [ ctx => ctx.path.startsWith('/api'), /^\/foo$/, '/bar'], // support Array // ... }, }; ``` __注意:如果存在 match 则忽略 ignore。__ ## API ### ctx.isSafeDomain(domain) 是否为安全域名。安全域名在配置中配置,见 `ctx.redirect` 部分 ## 接口限制 ### csrf __使用__ * `ctx.csrf` 获取 csrf token 一般在 POST 表单时使用。 页面渲染时,将 `ctx.csrf` 作为 form 隐藏域或 query string 渲染在页面上。(`_csrf` 作为 key) 在提交表单时,带上 token 即可。 #### 通过 formData 上传时使用 csrf 浏览器端 html 代码: ```html
``` ### ctoken ajax 防跨站攻击。 __使用__ 在 ajax 请求时,以 `ctoken` 为 name 带上 ctoken 即可。 ctoken 从 cookie 中获取 __安全开发者约定__ * `ctx.ctoken` 获取 ctoken 的逻辑。使用者不要调用,安全插件内部使用。 * `ctx.setCTOKEN()` 设置 ctoken 的逻辑。使用者不要调用,安全插件内部使用。 * `ctx.assertCTOKEN()` ctoken 校验逻辑。使用者不要调用,安全插件内部使用。 * `ctx.setCTOKEN()`会将cookie设置到主域名下,主要考虑主域名下其他子域名对应的应用之间的互相调用。例如 A.xx.com 域种了 ctoken,会设置cookie到xx.com域上,在 B.xx.com 域的时候可以利用 ctoken 去请求,在 A 域 jsonp 请求 B 域的时候,B 域也可以验证 ctoken。 可拓展实现。例如 ctoken token 存在什么 cookie,存什么字段等,都可以通过以上两个接口拓展。 #### 配置项 ```js exports.security = { csrf: { type: 'ctoken', // 可以是 ctoken / referer / all, 默认为 ctoken useSession: false, // 如果设为 true,secret 将存储在 session 中 ignoreJSON: false, // 如果设为 true ,将忽略 json 请求 cookieName: 'csrfToken', // csrf 的 token 在 cookie 中存储的 key 名称 sessionName: 'csrfToken', // csrf 的 token 在 session 中存储的 key 名称 headerName: 'x-csrf-token', // csrf token 在 header 中的名称 bodyName: '_csrf', // csrf token 在 body 中的名称 queryName: '_csrf', // csrf token 在 query 中的名称 rotateWhenInvalid: false, // csrf invalid 时刷新 token,用于同域名下多个业务 token 可能互相影响的情况 refererWhiteList: [], // referer 白名单 supportedRequests: [ // 支持的 url path pattern 和方法,根据配置名单由上至下匹配 url path 正则,建议在自定义时配置 {path: /^\//, methods:['POST','PATCH','DELETE','PUT','CONNECT']} 为兜底规则 {path: /^\//, methods:['POST','PATCH','DELETE','PUT','CONNECT']}, ], }, } ``` 注意,methods 可以为空, 如果将 supportedRequests 设置为`supportedRequests: [{path: /^\//, methods:[]}]`, 那么等效于关闭 csrf 防御。 ### safe redirect * `ctx.redirect(url)` 如果不在配置的白名单内,则禁止 * `ctx.unsafeRedirect(url)` 不建议使用 安全方案覆盖了默认的`ctx.redirect`方法,所有的跳转均会经过安全域名的判断。 用户如果使用`ctx.redirect`方法,需要在应用的配置文件中做如下配置: ```js exports.security = { domainWhiteList:['.domain.com'], // 安全白名单,以.开头 }; ``` 若用户没有配置 `domainWhiteList` 或者 `domainWhiteList` 数组内为空,则默认会对所有跳转请求放行,即等同于`ctx.unsafeRedirect(url)`。同时域名和 url 检查时不区分大小写。 ### jsonp 使用 [jsonp-body](https://github.com/node-modules/jsonp-body),在 egg context 中实现,并不再 egg-security 中。 防御内容: * callback函数名词最长50个字符限制 * callback函数名只允许"[","]","a-zA-Z0123456789_", "$" ".",防止一般的 xss,utf-7 xss等攻击 可定义配置: * callback 默认 `_callback`,可以改名 * limit - 函数名 length 限制,默认 50 ## helper ### .escape() 对字符串进行 xss 过滤,安全性最高的过滤方式。 ```js const str = '><'; console.log(ctx.helper.escape(str)); // => ><script>alert("abc") </script>< ``` 在 nunjucks 模板中,默认进行 escape,不需要显式调用。 ### .surl() url 过滤。 用于在html标签中中要解析 url 的地方(比如 `