【问题标题】:Spring Sessions HttpSession unable to completely replace JSESSIONIDSpring Sessions HttpSession 无法完全替换 JSESSIONID
【发布时间】:2016-07-17 01:43:05
【问题描述】:

我正在考虑将用户会话从应用程序级别移动到 Redis 实例。我相信我已根据文档 (http://docs.spring.io/spring-session/docs/current/reference/html5/#httpsession) 正确设置了所有内容,但我没有看到我所期望的行为并且认为我在某个地方错过了一步。

应用程序当前使用的是 HttpSession,所以我只是在上下文中添加了以下内容:

<context:annotation-config/>
<util:constant static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>
<beans:bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
<beans:bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="HOSTNAME" p:port="6379" />

在 web.xml 中添加了以下内容:

<filter>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

应用程序可以很好地构建、部署和加载页面,但是当我查看页面上的 cookie 时,我同时拥有 JSESSIONID 和 SESSION。我知道 JSESSIONID 被 Spring Security 使用,看起来 SESSION 被 Spring Session 使用。当我查看 redis 内部时,看起来 SESSION 是正在存储的。

另一个问题是自定义会话对象(使用 session.setAttribute 添加)没有显示在会话中。会话中显示的唯一内容是登录后,并且是 SPRING_SECURITY_CONTEXT 对象。当我删除 Spring Session 过滤器时,这些对象被添加到会话中就好了。

这是正常行为,还是因为我的设置有一些奇怪的冲突?

【问题讨论】:

标签: spring redis spring-session


【解决方案1】:

我遇到了同样的问题,最后发现是因为我的 web.xml 中声明的过滤器顺序错误。请求通过的第一个过滤器是 spring 安全过滤器,它在响应中设置 JSESSIONID cookie,然后 spring 会话存储库过滤器开始发挥作用,设置它自己的 SESSION cookie。更改顺序以便 spring 会话存储库过滤器首先执行其操作后,一切正常。

【讨论】:

【解决方案2】:

遇到了同样的问题。但是过滤器排序没有帮助。

当 JSESSIONID 传入请求时,它可以是 SESSION 和 JSESSIONID 响应,然后 spring session 将添加 SESSION cookie 和提供的 cookie(您可以清理请求中的 cookie 以仅接收 SESSION)。

发生在我这种情况的原因是:

默认情况下 cookie 由应用程序服务器(tomcat)提供,当我添加 spring 会话时,cookie 将由 spring 提供。 tomcat 的默认值为 JSESSIONID,spring (DefaultCookieSerializer.class) 的默认值为 SESSION

为了解决这个问题,我只是在 WEB.xml 中指定了 cookie 名称:

<session-config>
    <cookie-config>
        <name>JSESSIONID</name>
    </cookie-config>
</session-config>

这将为 tomcat 和 spring 会话过滤器指定 cookie 名称

【讨论】:

    【解决方案3】:

    我遇到了同样的问题。问题是 tomcat 会添加 JSESSIONID cookie 作为响应。所以我添加了CookieSerializer 并解决了问题。

    @Bean
    public CookieSerializer cookieSerializer() {
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        serializer.setCookieName("JSESSIONID"); 
        serializer.setCookiePath("/"); 
        serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$"); 
        return serializer;
    }
    

    另外不要忘记在tomcat中更改context.xml,如下所示:

    <Context cookies="false">
        ....
    </Context>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-03
      • 2011-03-06
      • 2016-09-12
      • 2021-09-11
      • 2016-09-28
      • 2015-10-17
      • 2023-03-19
      • 2019-06-25
      相关资源
      最近更新 更多