CSP nonce/hash 管理与构建集成最佳实践概述CSP中使用nonce或hash可允许受控内联脚本。结合构建流水线生成并注入,可实现自动化、安全的策略管理。服务端注入noncefunction 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> 构建阶段生成hashimport { 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治理方案。

发表评论 取消回复