如何在 Next.js 中配置 Content-Security-Policy(CSP)头?

解读

该问题考察候选人对Next.js中HTTP安全头配置的理解,特别是Content-Security-Policy(CSP)的实现方式。CSP是防御XSS、数据注入等攻击的核心机制,需结合Next.js的框架特性(如SSR/SSG)和实际业务场景(如第三方资源调用)进行配置。在中文开发场景中,还需注意国内网络环境下资源加载的合规性要求。

知识点

  1. Next.js中CSP配置的三种主要方式:next.config.js、中间件、自定义头
  2. CSP头核心指令:script-src、style-src、img-src、connect-src等
  3. 静态资源加载策略:使用nonce、hash、unsafe-inline等关键字的合理配置
  4. SSR/SSG模式下的CSP差异:动态内容与静态内容的策略适配
  5. 安全与功能的平衡:避免过度限制导致页面异常

答案

在Next.js中配置CSP需通过以下步骤实现:

1. 基础配置(next.config.js)

// next.config.js
module.exports = {
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.headers = {
        'Content-Security-Policy': [
          "default-src 'self'",
          "script-src 'self' https://example.com:443",
          "style-src 'self' https://example.com:443",
          "img-src 'self' data: https://example.com:443",
          "connect-src 'self' https://example.com:443",
          "frame-src 'none'"
        ].join('; ')
      }
    }
    return config
  }
}

2. 中间件动态配置

// middleware.js
export const config = {
  matcher: '/:path*',
};

export function middleware(req, res) {
  res.setHeader('Content-Security-Policy', 
    "script-src 'self' https://example.com:443; style-src 'self' https://example.com:443; img-src 'self' data: https://example.com:443");
  return NextResponse.next();
}

3. 自定义头配置(适用于API路由)

// pages/api/example.js
export default function handler(req, res) {
  res.setHeader('Content-Security-Policy', 
    "script-src 'self' https://example.com:443; style-src 'self' https://example.com:443");
  res.status(200).json({ message: 'CSP configured' });
}

配置时需注意:

  • 使用'self'限制资源来源
  • 通过unsafe-inline允许内联脚本(需谨慎使用)
  • 对第三方资源(如CDN、统计代码)需明确指定域名
  • 在SSG模式下需确保静态资源路径匹配
  • 使用nonce或hash实现动态脚本加载时,需配合Webpack插件生成对应值

拓展思考

在中文开发场景中,需额外注意:

  1. 国内CDN资源(如阿里云、腾讯云)的域名需添加到CSP策略中
  2. 对于需要加载的本地资源(如/public目录下的文件),应使用'self'或绝对路径
  3. 若使用unsafe-inline,需配合report-uri指令上报违规行为
  4. 在SSR模式下,需确保CSP头在服务器端渲染时正确注入
  5. 对于国际化站点,需通过connect-src配置多语言服务端地址
  6. 使用img-src时,需考虑数据URI编码的兼容性问题
  7. 配置完成后需通过curl -I [url]验证头是否正确发送
  8. 在开发阶段建议使用report-uri收集违规报告,逐步优化策略