[11] SessionManagementFilter

SessionManagementFilter

介紹

該Filter的主要作用是,當請求經過過濾器是 ,判斷緩存中是否有同一session id的請求,如果不存在則從上下文中獲取身份認證信息,並使用SessionAuthenticationStrategy對身份認證信息執行必要的操作,比如重新生成session id來防止session-fixation攻擊。過濾器中有2個比較重要的全局變量,分別是SessionAuthenticationStrategy、SecurityContextRepository。SessionAuthenticationStrategy實例的實現是CompositeSessionAuthenticationStrategy,是一個複合型的會話認證策略,默認情況下僅包含一個ChangeSessionIdAuthenticationStrategy,用於改變session的id,可以防止session fixation攻擊(建議百度)。SecurityContextRepository用戶將SecurityContext上下文保存到session中,但是默認情況SecurityContextRepository的實現是NullSecurityContextRepository,可以通過修改配置爲SessionCreationPolicy.IF_REQUIRED,進而給Filter注入HttpSessionSecurityContextRepository的實現,具體如何進行配置以及配置注入的代碼分析可以參照SecurityContextPersistenceFilter這篇文章。

代碼分析

步驟1

當請求經過SessionManagementFilter時,需要判斷緩存中是否已經存在了同一session id的請求了,只有不存在時,才從上下文中取身份認證信息,並通過SessionAuthenticationStrategy對authentication進行認證操作,認證成功後寫入到緩存中,代碼如下:

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);
	//判斷repo中是否未存儲過同一session id請求
    if (!securityContextRepository.containsContext(request)) {
        //從上下文中或身份認證信息
        Authentication authentication = SecurityContextHolder.getContext()
                .getAuthentication();
		//身份認證信息非空,並且不是匿名認證
        if (authentication != null && !trustResolver.isAnonymous(authentication)) {
            try {
                //這裏CompositeSessionAuthenticationStrategy
                //1. ChangeSessionIdAuthenticationStrategy進行驗證
                sessionAuthenticationStrategy.onAuthentication(authentication,
                        request, response);
            }
            catch (SessionAuthenticationException e) {
                SecurityContextHolder.clearContext();
                failureHandler.onAuthenticationFailure(request, response, e);

                return;
            }
            //將上下文中的身份認證信息存儲的session中
            securityContextRepository.saveContext(SecurityContextHolder.getContext(),
                    request, response);
        }
        else {
            // No security context or authentication present. Check for a session
            // timeout
            if (request.getRequestedSessionId() != null
                    && !request.isRequestedSessionIdValid()) {
                if (invalidSessionStrategy != null) {
                    invalidSessionStrategy
                            .onInvalidSessionDetected(request, response);
                    return;
                }
            }
        }
    }

    chain.doFilter(request, response);
}

步驟2

sessionAuthenticationStrategy.onAuthentication()這行代碼筆者有個疑問,sessionAuthenticationStrategy持有的策略默認只有一個ChangeSessionIdAuthenticationStrategy,這個策略使用修改session 的session id的,但是在筆者實際調用中始終hadSessionAlready=false,但筆者認爲不應該修改alwaysCreateSession的默認值,因此代碼始終執行不到修改session id的代碼段,代碼如下:

public void onAuthentication(Authentication authentication,
        HttpServletRequest request, HttpServletResponse response) {
    boolean hadSessionAlready = request.getSession(false) != null;
	//如果session不存在,就無法發起session攻擊,直接返回即可
    if (!hadSessionAlready && !alwaysCreateSession) {
        // Session fixation isn't a problem if there's no session

        return;
    }

    //session已經存在,一下操作是替換session id
    // Create new session if necessary
    HttpSession session = request.getSession();

    if (hadSessionAlready && request.isRequestedSessionIdValid()) {

        String originalSessionId;
        String newSessionId;
        Object mutex = WebUtils.getSessionMutex(session);
        synchronized (mutex) {
            // We need to migrate to a new session
            originalSessionId = session.getId();

            session = applySessionFixation(request);
            newSessionId = session.getId();
        }

        if (originalSessionId.equals(newSessionId)) {
            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");
        }

        onSessionChange(originalSessionId, session, authentication);
    }
}

步驟3

HttpSessionSecurityContextRepository#saveContext()方法最終會調到createNewSessionIfAllowed(),有個全局變量十分重要,allowSessionCreation的值決定着session能否成功被創建,我們可以配置SessionCreationPolicy爲IF_REQUIRED或者ALWAYS。Spring Security SessionCreationPolicy的配置在ResourceServerConfigurerAdapter(資源服務配置)和AuthorizationServerSecurityConfigurer(認證服務配置),我們在微服務中使用Spring Security時,往往登錄、登出、檢查TOKEN調認證服務接口,而在其他業務系統中往往引入資源服務認證配置。但是對於授權認證服務,其代碼有點不太一樣,即使配置了也沒有什麼用,AuthorizationServerSecurityConfigurer的這段代碼又晚於我們的自定義配置執行,因此這裏的設置放入shareObject的SecurityContextRepository,最終都會被替換爲NullSecurityContextRepository,代碼如下:

private HttpSession createNewSessionIfAllowed(SecurityContext context) {
    if (isTransientAuthentication(context.getAuthentication())) {
        return null;
    }

    if (httpSessionExistedAtStartOfRequest) {
        return null;
    }

    if (!allowSessionCreation) {
        return null;
    }
    // Generate a HttpSession only if we need to

    if (contextObject.equals(context)) {
        return null;
    }

    try {
        return request.getSession(true);
    }
    catch (IllegalStateException e) {
    }

    return null;
}

@Override
public void init(HttpSecurity http) throws Exception {

    registerDefaultAuthenticationEntryPoint(http);
    if (passwordEncoder != null) {
        ClientDetailsUserDetailsService clientDetailsUserDetailsService = new ClientDetailsUserDetailsService(clientDetailsService());
        clientDetailsUserDetailsService.setPasswordEncoder(passwordEncoder());
        http.getSharedObject(AuthenticationManagerBuilder.class)
                .userDetailsService(clientDetailsUserDetailsService)
                .passwordEncoder(passwordEncoder());
    }
    else {
        http.userDetailsService(new ClientDetailsUserDetailsService(clientDetailsService()));
    }
    //這裏默認使用的是NullSecurityContextRepository
    http.securityContext().securityContextRepository(new NullSecurityContextRepository()).and().csrf().disable()
            .httpBasic().realmName(realm);
    if (sslOnly) {
        http.requiresChannel().anyRequest().requiresSecure();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章