333
schangxiang@126.com
2025-09-19 18966e02fb573c7e2bb0c6426ed792b38b910940
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'use strict';
 
const compose = require('koa-compose');
const path = require('path');
const assert = require('assert');
const createMatch = require('egg-path-matching');
 
module.exports = (_, app) => {
  const options = app.config.security;
  const middlewares = [];
  const defaultMiddleware = (options.defaultMiddleware || '').split(',');
 
  if (options.match || options.ignore) {
    app.coreLogger.warn('[egg-security] Please set `match` or `ignore` on sub config');
  }
 
  // format csrf.cookieDomain
  const orginalCookieDomain = options.csrf.cookieDomain;
  if (orginalCookieDomain && typeof orginalCookieDomain !== 'function') {
    options.csrf.cookieDomain = () => orginalCookieDomain;
  }
 
  defaultMiddleware.forEach(middlewareName => {
 
    middlewareName = middlewareName.trim();
 
    const opt = options[middlewareName];
    assert(opt === false || typeof opt === 'object',
      `config.security.${middlewareName} must be an object, or false(if you turn it off)`);
 
    if (opt === false || opt && opt.enable === false) {
      return;
    }
 
    if (middlewareName === 'csrf' && opt.useSession && !app.plugins.session) {
      throw new Error('csrf.useSession enabled, but session plugin is disabled');
    }
 
    // use opt.match first (compatibility)
    if (opt.match && opt.ignore) {
      app.coreLogger.warn('[egg-security] `options.match` and `options.ignore` are both set, using `options.match`');
      opt.ignore = undefined;
    }
    if (!opt.ignore && opt.blackUrls) {
      app.deprecate('[egg-security] Please use `config.security.xframe.ignore` instead, `config.security.xframe.blackUrls` will be removed very soon');
      opt.ignore = opt.blackUrls;
    }
    opt.matching = createMatch(opt);
 
    const fn = require(path.join(__dirname, '../../lib/middlewares', middlewareName))(opt, app);
    middlewares.push(fn);
    app.coreLogger.info('[egg-security] use %s middleware', middlewareName);
  });
  app.coreLogger.info('[egg-security] compose %d middlewares into one security middleware',
    middlewares.length);
 
  return compose(middlewares);
};