我有一个配置有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>

最佳答案

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

在您的ContainerRequestFilter中添加以上行。它像一种魅力。

并查看此链接。

Jersey REST + CORS + Jquery AJAX CALL

关于tomcat - 将CORS过滤器应用于Tomcat 4XX响应,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26765644/

10-14 11:22