csp 设置 nonce

简单记录一下 需求,严格csp,渲染google地图

1.首先服务端生成nonce值,然后!!需要获取html文件,并且把里面的nonce值替换。 这样客户端style标签里面的内容就可以使用了

google地图就是自己去获取了style标签里面的nonce值!!!!

javascript 复制代码
import express from 'express'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
import { randomBytes } from 'crypto'
import fs from 'fs'

// 获取当前文件路径
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const app = express()
const PORT = 3000

// 生成 nonce 值
function generateNonce() {
  return randomBytes(16).toString('base64')
}

// 静态文件服务(先于 CSP 中间件)

app.use(
  express.static(join(__dirname, '../dist'), {
    index: false, // 正确禁用自动返回 index.html
  }),
)
// CSP 中间件
app.use((req, res, next) => {
  const nonce = generateNonce()
  res.locals.nonce = nonce

  res.setHeader(
    'Content-Security-Policy',
    `default-src 'self';style-src 'self' 'nonce-${nonce}' https://maps.gstatic.com https://fonts.googleapis.com;font-src 'self' https://fonts.gstatic.com;script-src 'self'  https://www.gstatic.cn/recaptcha/ https://www.gstatic.com/recaptcha/ https://maps.googleapis.com ;img-src 'self' data: https://maps.googleapis.com https://maps.gstatic.com https://*.googleapis.com https://*.gstatic.com *.google.com *.googleusercontent.com;frame-src 'self' ;connect-src 'self' https://maps.googleapis.com;`,
  )
  next()
})

// HTML 路由处理
app.get('*', (req, res) => {
  const nonce = res.locals.nonce
  const htmlPath = join(__dirname, '../dist/index.html')

  try {
    let html = fs.readFileSync(htmlPath, 'utf8')

    // 调试:检查替换前内容
    console.log('替换前是否包含 csp_nonce:', html.includes('csp_nonce'))

    // 多种替换方式确保覆盖
    html = html
      .replace(/nonce="[^"]*"/g, `nonce="${nonce}"`) // 替换所有现有 nonce
      .replace(/__CSP_NONCE__/g, nonce) // 备用占位符格式

    // 调试:检查替换结果
    console.log('替换后 nonce 值:', html.match(/nonce="([^"]*)"/)?.[1])

    res.send(html)
  } catch (err) {
    console.error('读取 HTML 文件失败:', err)
    res.status(500).send('Server Error')
  }
})

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`)
})

vue-html文件设置一个style标签,让服务器端去替换

google 地图自己会去找到并动态生成style标签,就不会行内样式报错啦!

相关推荐
Light604 小时前
CSS逻辑革命:原生if()函数如何重塑我们的样式编写思维
前端·css·响应式设计·组件化开发·css if函数·声明式ui·现代css
蜡笔小嘟4 小时前
宝塔安装dify,更新最新版本--代码版
前端·ai编程·dify
ModyQyW5 小时前
HBuilderX 4.87 无法正常读取 macOS 环境配置的解决方案
前端·uni-app
bitbitDown5 小时前
我的2025年终总结
前端
五颜六色的黑5 小时前
vue3+elementPlus实现循环列表内容超出时展开收起功能
前端·javascript·vue.js
wscats6 小时前
Markdown 编辑器技术调研
前端·人工智能·markdown
EnoYao6 小时前
Markdown 编辑器技术调研
前端·javascript·人工智能
JIngJaneIL6 小时前
基于java+ vue医院管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
JIngJaneIL7 小时前
基于java + vue校园跑腿便利平台系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
前端要努力7 小时前
月哥创业3年,还活着!
前端·面试·全栈