【问题标题】:Whitelisted CORS using Apache使用 Apache 将 CORS 列入白名单
【发布时间】:2015-01-04 20:32:43
【问题描述】:

我希望设置我的 (Red Hat Linux/Apache 2.2.3) 网站以允许来自用 Javascript 编写的 HTML5 应用程序的 Ajax 调用,这些脚本可能托管在其他地方。

这就是 CORS 的全部意义所在。

有很多关于如何通过 mod_headers 启用 CORS 的描述。几乎所有人都将 Access-Control-Allow-Origin 标头设置为“*”,从而将网站向全世界开放。

但同源政策的实施是有原因的,这种访问级别引发了真正的安全问题。

如何将我想要的网站(可能有几十个,但与我有业务关系的人的网站)列入白名单而不向全世界开放我的网站?

我看到的唯一讨论这个问题的讨论是http://blog.blakesimpson.co.uk/read/64-apache-configure-cors-headers-for-whitelist-domains 但是:

  1. 该页面虽然有见地,但并不详尽。
  2. 由于允许的来源数量较多,该方法看起来难以管理。

有安全意识的网络管理员在做什么?

【问题讨论】:

标签: ajax apache security cors


【解决方案1】:

您可以将所有列入白名单的域如下所示,还可以定义通用正则表达式匹配以更灵活地加入白名单域。

<IfModule mod_headers.c>

   ##########################################################################
   # 1.) ENABLE CORS PRE-FLIGHT REQUESTS
   # e.g. PUT, DELETE, OPTIONS, ...
   # we need to set Access-Control-Allow-Headers and
   # Access-Control-Allow-Methods for allowed domain(s)
   ##########################################################################

   # first check for pre-flight headers and set as environment variables
   # e.g. header method-a is set here
   SetEnvIf ^Access-Control-Request-Method$ "method-a" METHOD_A
   SetEnvIf ^Access-Control-Request-Headers$ "^Content-Type$" HEADER_A

   # set corresponding response pre-flight headers for allowed domain(s)
   Header set Access-Control-Request-Methods "method-a" env=METHOD_A
   Header set Access-Control-Request-Headers "content-type" env=HEADER_A

   # TODO: add allowed additional pre-flight requests here...

   #########################################################################
   # 2.) ENABLE CORS *SIMPLE REQUESTS* (vs. Pre-Flight Requests from above)
   # e.g. GET, POST and HEAD requests
   # we need to set Access-Control-Allow-Origin header for allowed domain(s)
   # also note that POST requests need to match one of the following
   # Content-Type:
   # 1) application/x-www-form-urlencoded
   # 2) multipart/form-data
   # 3) text/plain
   #########################################################################


   # e.g. origin = https://host-b.local
   SetEnvIfNoCase Origin "https://host-b.local" AccessControlAllowOrigin=$0
   Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin


   # generic regexp match for more flexibel use cases
   #SetEnvIfNoCase Origin "((http(s?))?://(www\.)?(host\-a|host\-b)\.local)(:\d+)?$" AccessControlAllowOrigin=$0
   #Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin

   # TODO: add additional whitelisted domain here...

</IfModule>

【讨论】:

    猜你喜欢
    • 2020-04-08
    • 2018-01-22
    • 1970-01-01
    • 2020-05-21
    • 2020-04-23
    • 2017-06-19
    • 2021-12-08
    • 2015-03-29
    • 2017-10-05
    相关资源
    最近更新 更多