使用 Apache 2.4 生成随机数(用于内容安全策略标头) [英] Generate a nonce with Apache 2.4 (for a Content Security Policy header)

查看:37
本文介绍了使用 Apache 2.4 生成随机数(用于内容安全策略标头)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在努力制定严格的内容安全政策 (https://csp.withgoogle.com/docs/strict-csp.html),这需要 Apache 在每次请求资源时创建一个 nonce,以便我们可以将这个 nonce 插入到 http 标头中.

We're working on creating a strict Content Security Policy (https://csp.withgoogle.com/docs/strict-csp.html) which necessitates Apache creating a nonce each time a resource is requested, so that we can insert this nonce into the http header.

我们如何使用 Apache 2.4 创建随机数?

How can we create a nonce with Apache 2.4?

我读过的所有 CSP 相关文档都说随机数只是在服务器上生成的随机字符串,包含在 CSP 标头中......"但没有找到任何信息如何使用 Apache 执行此操作.我们当然可以用应用程序代码来做到这一点,但通过 Apache 做到这一点似乎是一个更简洁的解决方案/将确保每个页面都获得 CSP 标头.

All of the CSP related documentation I've read says something to the effect of "A nonce is just a random string that's generated on the server, included in the CSP header..." but haven't found any info on how to do this with Apache. We could of course do this with app code, but doing it via Apache seems like a cleaner solution/will ensure every single page gets the CSP header.

推荐答案

您需要在服务器上生成 nonce,然后让 Apache 将该 nonce 传递给您的可以使用它的脚本.

You need to generate the nonce on the server, and then have Apache pass that nonce to your script where it can be used.

我们为 Apache 创建了一个开源模块来简化这个过程:mod_cspnonce.

We've created an open source module for Apache that simplifies this process: mod_cspnonce.

这是服务器端配置的一个简单示例:

Here's a simple example of the server-side config:

LoadModule headers_module modules/mod_headers.so
LoadModule cspnonce_module modules/mod_cspnonce.so

# add the CSP_NONCE to the "default-src"
Header add Content-Security-Policy "default-src 'self' 'nonce-%{CSP_NONCE}e';"

以下是在脚本中使用随机数的简单示例:

Here's a simple example of using the nonce in your script:

<script nonce="<?= $_SERVER['CSP_NONCE'] ?>">
  var inline = 1;
</script>

那个例子是 php,但你可以使用任何语言.

That example is php, but you can use any language.

这篇关于使用 Apache 2.4 生成随机数(用于内容安全策略标头)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆