天天看點

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屬性存在。

Spring Security與BlazeDS內建的FlexSession Invalid問題

       當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);
	}