[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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值