CORS - 如何在Apache的httpd.conf中忽略OPTIONS预检请求的身份验证?

时间:2014-07-03 14:28:41

标签: ajax apache .htaccess cors

我是CORS的新手,并且了解到浏览器发送的OPTIONS预检请求会排除用户凭据。 如何让过滤器(在httpd.conf中)以不同方式响应OPTIONS请求,即绕过身份验证?

这是我目前的配置:

<LocationMatch /api>
SetEnvIfNoCase Origin "https://(www\.)?(domain1\.com|domain2\.com)(:\d+)?$" AccessControlAllowOrigin=$0
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header set Access-Control-Allow-Credentials "true"
Header set Access-Control-Allow-Methods "GET,POST,DELETE,OPTIONS"
Header set Access-Control-Allow-Headers "Accept, Authorization, Origin, Content-Type"
AuthFormProvider ldap
AuthLDAPURL "ldap://localhost:10889/ou=Users,dc=work,dc=com?uid"
AuthLDAPGroupAttribute member
AuthLDAPGroupAttributeIsDN on
Require valid-user
ErrorDocument 401 /login.html
ErrorDocument 500 /error.html
AuthType form
AuthName realm
Session On
SessionMaxAge 1800
SessionDBDCookieName session path=/
ProxyPass  http://localhost:8080 timeout=31536000
AuthFormFakeBasicAuth On
</LocationMatch>

发出请求的javascript:

$.ajax({
        type : "DELETE",
        url : "https://www.domain1.com/api",
        xhrFields: {
            withCredentials: true,
        },
        success : function(data){

        },
});

我已经尝试了以下但没有运气:

(a)中

RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L,E=HTTP_ORIGIN:%{HTTP:ORIGIN}]

(b)中

<Limit OPTIONS>
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Credentials "false"
Header always set Access-Control-Allow-Headers "Accept, Authorization, Origin, Content-Type"
Header always set Access-Control-Allow-Methods "GET,POST,DELETE,OPTIONS,PUT"
</Limit>

(c)中

<Limit OPTIONS>
Allow for all
</Limit>

(d)

SetEnvIfNoCase Request_Method OPTIONS allowed

有什么想法吗?请帮忙!

1 个答案:

答案 0 :(得分:6)

我遇到了同样的问题,我今天在this question的帮助下解决了这个问题。基本上你的选择c。

我的conf结构是:

conf/httpd.conf <- normal stuff   
conf.d/ssl.conf <- set up ssl stuff  
conf.d/api.conf <- set specific stuff to api like Auth  
/var/www/.htaccess <- set specific stuff to api again   

这允许限制除OPTIONS

之外的所有内容

/conf.d/api.conf档案:

<Directory "/var/www/api">
  AllowOverride All
  Options FollowSymLinks

  <LimitExcept OPTIONS>
    Auth stuff here
    Mainly your Require statements
  </LimitExcept>
</Directory>

然后在我的.htaccess文件中设置标题。

require指令中的

The Apache manual声明“以这种方式应用的访问控制对所有方法都有效。这通常是需要的。如果您希望仅对特定方法应用访问控制,而留下其他方法方法不受保护,然后将Require语句放入<Limit> [或<LimitExcept>]部分。“

我必须确保我的应用程序可以处理OPTIONS,因为此设置没有自动返回。 Herehere可以看到如何重定向可能有效但不会在应用程序中处理某些内容。