Spring Security与BlazeDS集成的FlexSession Invalid问题

        先说现象:当用户登录以后,如果点击浏览器的后退按钮回到登录页面,这个时候用浏览器的前进按钮是可以再回到主页面的,但如果再想通过输入用户名/密码登录的时候,就会发现登录不了,系统会一直跳转到登录页面。查看后台的话会发现这个是因FlexSession invalid Exception 引起的。
       仔细想想觉得系统不应该会有这种bug啊,但是不管你觉得会不会,问题出现了,而且还非常容易重现。先查了下blazeds的jira,还真发现有人提过这个bug(
http://bugs.adobe.com/jira/browse/BLZ-350 ),但是看这个issue的comments说考虑会在版本4中改,又说在spring security中改更容易,还给了一个spring security jira的连接。

 

       果然,spring security jira中也有人提过这个bug(https://jira.springsource.org/browse/SEC-1109 ),看了下解决方案是通过实现自己的SessionAuthenticationStrategy在销毁/复制旧session的时候特殊处理“__flexSession”属性。
       也就是说双方都没改,只是提供了修复建议,默认配置还是会出现这个bug,有点意思,呵呵!那就查看下source code,自己探其究竟吧:

       先说blazeds,他提供了一个叫做HttpFlexSession的session监听器,他会去监听HttpSession,从而维护了一套与HttpSession对应的属性,而它自己也会作为HttpSession的__flexSession属性存在。


       当HttpSession销毁的时候,HttpFlexSession的sessionDestory方法触发,该方法会清理HttpFlexSession所占的资源,从而使得其自身invalidate(),即当前的这个HttpFlexSession已经不可用了,但是他并不会将自己从HttpSession中清理掉,也没有将自己设置为null。参考代码:

 

public void sessionDestroyed(HttpSessionEvent event)
    {
        HttpSession session = event.getSession();
        Map httpSessionToFlexSessionMap = getHttpSessionToFlexSessionMap(session);
        HttpFlexSession flexSession = (HttpFlexSession)httpSessionToFlexSessionMap.remove(session.getId());
        if (flexSession != null)
        {
            // invalidate the flex session
            flexSession.superInvalidate();

            // Send notifications to attribute listeners if needed.
            // This may send extra notifications if attributeRemoved is called first by the server,
            // but Java servlet 2.4 says session destroy is first, then attributes.
            // Guard against pre-2.4 containers that dispatch events in an incorrect order, 
            // meaning skip attribute processing here if the underlying session state is no longer valid.
            try
            {
                for (Enumeration e = session.getAttributeNames(); e.hasMoreElements(); )
                {
                    String name = (String) e.nextElement();
                    if (name.equals(SESSION_ATTRIBUTE))
                        continue;
                    Object value = session.getAttribute(name);
                    if (value != null)
                    {
                        flexSession.notifyAttributeUnbound(name, value);
                        flexSession.notifyAttributeRemoved(name, value);
                    }
                }
            }
            catch (IllegalStateException ignore)
            {
                // NOWARN
                // Old servlet container that dispatches events out of order.
            }
        }
    }



 

      这个没有错,因为从blazeds的角度看,上面的一系列动作是在HttpSession销毁时候触发的,既然HttpSession都销毁了,也就没有必要再去一个已销毁的对象里remove掉属性(贸然的remove还可能有nullpointorexception)!
      再来看看Spring Security,当用户进行Authentication的时候(默认是提交j_spring_security_check请求)会经过SessionManagementFilter,若authentication已经存在(即已经认证过),该filter默认会调用SessionFixationProtectionStrategy的onAuthentication方法,该方法会复制已经存在的那个HttpSession的所有属性,然后就销毁之,接着会创建一个新的HttpSession并把刚刚复制的所有属性set到这个新session中。参考代码:

 

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        if (request.getAttribute(FILTER_APPLIED) != null) {
            chain.doFilter(request, response);
            return;
        }

        request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

        if (!securityContextRepository.containsContext(request)) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            if (authentication != null && !authenticationTrustResolver.isAnonymous(authentication)) {
             // The user has been authenticated during the current request, so call the session strategy
                try {
                    sessionStrategy.onAuthentication(authentication, request, response);
                } catch (SessionAuthenticationException e) {
                    // The session strategy can reject the authentication
                    logger.debug("SessionAuthenticationStrategy rejected the authentication object", e);
                    SecurityContextHolder.clearContext();
                    failureHandler.onAuthenticationFailure(request, response, e);

                    return;
                }
                // Eagerly save the security context to make it available for any possible re-entrant
                // requests which may occur before the current request completes. SEC-1396.
                securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);
            } else {
             // No security context or authentication present. Check for a session timeout
                if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
                    logger.debug("Requested session ID" + request.getRequestedSessionId() + " is invalid.");

                    if (invalidSessionUrl != null) {
                        logger.debug("Starting new session (if required) and redirecting to '" + invalidSessionUrl + "'");
                        request.getSession();
                        redirectStrategy.sendRedirect(request, response, invalidSessionUrl);

                        return;
                    }
                }
            }
        }

        chain.doFilter(request, response);
    }



 

 

public void onAuthentication(Authentication authentication, HttpServletRequest request, HttpServletResponse response) {
        boolean hadSessionAlready = request.getSession(false) != null;

        if (!hadSessionAlready && !alwaysCreateSession) {
            // Session fixation isn't a problem if there's no session

            return;
        }

        // Create new session if necessary
        HttpSession session = request.getSession();

        if (hadSessionAlready && request.isRequestedSessionIdValid()) {
            // We need to migrate to a new session
            String originalSessionId = session.getId();

            if (logger.isDebugEnabled()) {
                logger.debug("Invalidating session with Id '" + originalSessionId +"' " + (migrateSessionAttributes ?
                        "and" : "without") +  " migrating attributes.");
            }

            HashMap<String, Object> attributesToMigrate = createMigratedAttributeMap(session);

            session.invalidate();
            session = request.getSession(true); // we now have a new session

            if (logger.isDebugEnabled()) {
                logger.debug("Started new session: " + session.getId());
            }

            if (originalSessionId.equals(session.getId())) {
                logger.warn("Your servlet container did not change the session ID when a new session was created. You will" +
                        " not be adequately protected against session-fixation attacks");
            }

            // Copy attributes to new session
            if (attributesToMigrate != null) {
                for (Map.Entry<String, Object> entry : attributesToMigrate.entrySet()) {
                    session.setAttribute(entry.getKey(), entry.getValue());
                }
            }
        }
    }



 

       从Spring Security角度看,这个也没有错啊!已经认证过的用户再次认证,我的策略就是复制一个新的session。这也难怪双方都没有去改框架的代码。

       正如JIRA上的建议,也从源码可看到在SessionManagementFilter中,SessionAuthenticationStrategy是可以自己配置的:

public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionStrategy) {
        Assert.notNull(sessionStrategy, "authenticatedSessionStratedy must not be null");
        this.sessionStrategy = sessionStrategy;
    }



 

     所以,解决的一个方法便很简单了,不要使用SessionManagementFilter中默认的SessionFixationProtectionStrategy,而是实现自己的SessionAuthenticationStrategy并配置给SessionManagementFilter中即可。至于自己实现SessionAuthenticationStrategy,在将属性复制到新session的时候,判断下如果是HttpFlexSession就不要复制进去了,呵呵!

      上面的这个方法改动是最少的,就是写个新类实现SessionAuthenticationStrategy接口配置下。但是如果不想对Spring Security扩展,我觉得也可以用扩展blazeds的思路来实现。尝试了两种,第一种通过实现一个FlexSessionListener去监听HttpFlexSession,当触发sessionDestory的时候将HttpFlexSession.httpSession里的HttpFlexSession属性移除掉,但是这种方法不对的 ,因为这个方法被触发之前,httpSession里的所有属性已经被复制了,再移除已经无用。第二种,重写MessageBrokerServlet的service方法,因为异常的源头来自该servlet用了一个invalid的HttpFlexSession去获取Principal,所以只要再service方法之前先判断下当前的HttpFlexSession是否已经无效,无效的话我们就从当前的HttpSession中移除这个无效的HttpFlexSession即可。这样,就能保证MessageBrokerServlet中所用的HttpFlexSession一定是有效的。

 

@Override
	public void service(HttpServletRequest req, HttpServletResponse res) {
		HttpSession httpSession = req.getSession(true);
		HttpFlexSession flexSession = (HttpFlexSession)httpSession.getAttribute(XXWebServlet.SESSION_ATTRIBUTE);
		if( flexSession != null && !flexSession.isValid()){
			httpSession.removeAttribute(XXWebServlet.SESSION_ATTRIBUTE);
		}
		super.service(req, res);
	}



 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值