CORS Filter无法维护会话

时间:2017-03-22 11:55:34

标签: google-chrome session struts2 cors

我有一个基于Struts2的应用程序,它接收来自另一个应用程序(跨域)的请求。为此,我在struts2过滤器之前的web.xml中添加了CORS过滤器:

    <filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
        <init-param>
            <param-name>cors.allowed.origins</param-name>
            <param-value>*</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.methods</param-name>
            <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.headers</param-name>
            <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,X-Test-Header
            </param-value>
        </init-param>
        <init-param>
            <param-name>cors.exposed.headers</param-name>
            <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials
            </param-value>
        </init-param>
        <init-param>
            <param-name>cors.support.credentials</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>cors.preflight.maxage</param-name>
            <param-value>1000</param-value>
        </init-param>
    </filter>
     <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
   <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

创建新会话的应用程序的第一个请求正常工作。但是在随后的请求中,当我尝试在我的动作类中访问同一个会话时,我得到null。以下是我要做的事情:

HttpSession session = ServletActionContext.getRequest().getSession(false);

以上工作通常很好,但在这里会话可能会以某种方式失效。 我正在Chrome浏览器中测试此功能,并启用了Allow-Control-Allow-Origin:*扩展程序。以下是我的POST请求标头在控制台中的显示方式:

Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:9
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost:7070
Origin:http://evil.com/
Referer:http://testdevsvr:8989/SmartAdministration/home
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36

我想知道我是否遗漏了配置中的某些内容或其他错误导致我无法继续进行操作。

1 个答案:

答案 0 :(得分:1)

我终于根据here给出的建议执行这两个步骤来维持会话:

1。)在我的所有ajax调用中包含以下代码段:

  xhrFields: {withCredentials: true}

2.。)在我的web.xml中包含此配置:

     <session-config>
        <session-timeout>30</session-timeout> 
            <cookie-config>
                <http-only>false</http-only>
            </cookie-config>
    </session-config>