我如何配置tomcat不对CORS OPTIONS请求执行身份验证或授权

时间:2015-01-29 23:12:07

标签: tomcat authentication cors

我正在尝试向Tomcat托管的网络应用程序发出CORS请求(详情如下)。

我已经设置了CORS标头内容(在Apache httpd.conf中)并且它似乎正在工作,但是由Chrome生成的(我假设)飞行前OPTIONS请求,它没有auth标头,但是失败了错误401。

我认为我需要说服Apache或Tomcat不要为OPTIONS请求做任何auth,而是用200来完成它。

我正在吠叫正确的树吗? 2)我应该在Tomcat(web.xml)中放置一个CORS过滤器而不是Apache(httpd.conf)中的一组标头集吗?
3)我无法找到如何配置apache来做到这一点 - 任何指针?我发现最近的暗示是@Thomas Broyer去年四月回复Enable CORS for tomcat applications with credentials support因此:

you have to declare a <security-constraint> with <http-method>OPTIONS</http-method> and no <auth-constraint>."

非常感谢任何帮助!我试图解决这个问题多天...

===================

现状:

请求:

Remote Address:54.245.121.9:80
Request URL:http://ec2-54-245-121-9.us-west-2.compute.amazonaws.com/v1/plant
Request Method:OPTIONS
Status Code:401 Unauthorized
Request Headersview parsed
OPTIONS /v1/plant HTTP/1.1
Host: ec2-54-245-121-9.us-west-2.compute.amazonaws.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://ec2-54-245-121-9.us-west-2.compute.amazonaws.com:8084
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36
Access-Control-Request-Headers: accept, authorization, content-type
Accept: */*
Referer: http://ec2-54-245-121-9.us-west-2.compute.amazonaws.com:8084/add
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,de;q=0.6

响应:

Headersview parsed
HTTP/1.1 401 Unauthorized
Date: Thu, 29 Jan 2015 23:00:34 GMT
Server: Apache-Coyote/1.1
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
WWW-Authenticate: Basic realm="Realm"
Content-Type: text/html;charset=utf-8
Content-Language: en
Content-Length: 1104
Access-Control-Allow-Origin: http://ec2-54-245-121-9.us-west-2.compute.amazonaws.com:8084
Vary: Origin
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: origin, accept, authorization, content-type, x-requested-with
Access-Control-Allow-Credentials: true
Connection: close

==============================

有关我的应用的更多信息:

我有一个MEAN web-app,其node.js服务器运行于:8084。

现有的Tomcat / Java Web应用程序运行的是REST API:80(由Apache前端)......

客户端中的基于Angular.js的js代码(在我的测试中使用Chrome)调用REST API。

因为端口8084!=端口80,它是一个CORS请求。

2 个答案:

答案 0 :(得分:0)

tomcat.apache.org/tomcat-7.0-doc/images/cors-flowchart.png上的Tomcat CORS过滤器流程图说,如果它发现请求是预检,并且一切都是copacetic,那么它会倒带过滤器链'。这意味着不会进行进一步的处理 - 比如auth。所以答案似乎是使用org.apache.catalina.filters.CorsFilter而不是通过httpd.conf插入标题。

答案 1 :(得分:0)

也许this answer可以提供帮助。简而言之:

<security-constraint>
    <web-resource-collection>
        <url-pattern>/*</url-pattern>
        <http-method>OPTIONS</http-method>
    </web-resource-collection>
    <!-- no auth-constraint here -->
</security-constraint>