---

title: CSP nonce/hash 管理与构建集成最佳实践

keywords:

  • CSP
  • nonce
  • hash
  • 构建集成
  • 脚本白名单
  • 内联脚本治理

description: 通过构建阶段生成nonce与hash并在服务端注入,结合脚本白名单与内联治理,实现可验证的CSP策略管理与落地。

categories:

  • 文章资讯
  • 编程技术

---

CSP nonce/hash 管理与构建集成最佳实践

概述

CSP中使用nonce或hash可允许受控内联脚本。结合构建流水线生成并注入,可实现自动化、安全的策略管理。

服务端注入nonce

function makeNonce(): string {
  const bytes = crypto.randomBytes(16)
  return bytes.toString('base64')
}

function setCspWithNonce(res: any, nonce: string) {
  res.setHeader('Content-Security-Policy', `script-src 'self' 'nonce-${nonce}'; object-src 'none'; base-uri 'self'`)
}

前端使用nonce

<script nonce="{{nonce}}">window.__BOOTSTRAP__ = {};</script>
<script nonce="{{nonce}}" src="/static/app.js"></script>

构建阶段生成hash

import { createHash } from 'crypto'

function sha256Base64(s: string): string {
  return createHash('sha256').update(s).digest('base64')
}

function buildCspHashForInline(code: string): string {
  const h = sha256Base64(code)
  return `'sha256-${h}'`
}

自动化集成

function injectCsp(res: any, inlineCodes: string[]) {
  const hashes = inlineCodes.map(code => buildCspHashForInline(code))
  res.setHeader('Content-Security-Policy', `script-src 'self' ${hashes.join(' ')}; object-src 'none'`)
}

运维要点

  • 优先使用外部脚本与nonce,减少内联片段数量
  • 构建阶段对内联片段生成hash并与版本绑定
  • 对策略变更进行审计与回滚,确保兼容性与安全性

通过nonce/hash与构建集成,可实现自动化与安全兼容的CSP治理方案。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部