将CORS过滤器应用于Tomcat 4XX响应

时间:2014-11-05 19:39:33

标签: tomcat jersey cors basic-authentication http-status-code-401

我有一个配置了BASIC身份验证的Tomcat 6服务器通过CORS过滤器向AngularJS前端提供REST API。使用标头中提供的有效凭据,一切正常。如果未批准身份验证(401,403),则不会附加CORS标头,并且客户端无法确定状态代码。有没有办法让我配置CORS过滤器来影响这些响应?有谁知道我在哪里可以找到一个图表,显示过滤器和身份验证如何适合Tomcat的架构?

我在Chrome中遇到的错误是:http://imgur.com/2hTEpiu(我没有足够的声誉来发布图片)


安全性的配置如下:

<security-role>
    <role-name>phys_user</role-name>
</security-role>

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Rest Service</web-resource-name>
        <url-pattern>/rest/*</url-pattern>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
        <role-name>phys_user</role-name>
    </auth-constraint>
</security-constraint>

<login-config>
    <auth-method>BASIC</auth-method>
</login-config>

我尝试在Jersey上注册自定义ContainerResponseFilter:

@PreMatching
public class ResponseCorsFilter implements ContainerResponseFilter {

    @Override
    public ContainerResponse filter(ContainerRequest req, ContainerResponse res) {
        Response.ResponseBuilder rb = Response.fromResponse(res.getResponse());
        rb.header("Access-Control-Allow-Origin", "*")
          .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");

        String reqHeader = req.getHeaderValue("Access-Control-Request-Headers");
        if(reqHeader != null && !reqHeader.equals(""))
            rb.header("Access-Control-Allow-Headers", reqHeader);

        res.setResponse(rb.build());
        return res;
    }
}

...以及web.xml

<init-param>
    <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
    <param-value>cm.security.ResponseCorsFilter</param-value>
</init-param>

我也尝试过使用库中的CORS过滤器:

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    <init-param>
        <param-name>cors.allowOrigin</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedMethods</param-name>
        <param-value>GET, POST, OPTIONS</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedHeaders</param-name>
        <param-value>accept, authorization, origin</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportsCredentials</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

1 个答案:

答案 0 :(得分:0)

if(method.equals(GeneralEnums.HttpMethodType.OPTIONS.toString())){             抛出新的WebApplicationException(Status.OK);         }

在ContainerRequestFilter中添加以上行。它就像一个魅力。

还要看这个链接。

Jersey REST + CORS + Jquery AJAX CALL