配置spring-security对redis中session的同步处理,通过sessionRegistry统计在线用户

史英睿
2023-12-01

问题描述:

登录用户的session在redis失效、清除或者用户退出系统后,系统中的sessionRegistry中session依然存在,并未同步失效

系统架构:

Springboot2 + SpringSecurity + spring-session-data-redis + Redis

1. Redis配置(当然可以只加注解,使用默认配置)
/** redis配置 */
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    // 自定义缓存key生成策略
    @Override
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
                StringBuffer sb = new StringBuffer();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    // 缓存管理器
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        //反序列化问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 解决存储乱码问题
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                // 缓存过期时间1hours  以application.yml配置文件中的优先级更高
                .entryTtl(Duration.ofHours(1))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();

        RedisSerializer<String> redisSerializer = new StringRedisSerializer();

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        return template;
    }
}

2. WebSecurity的配置 (重点)

@Configuration
@EnableWebSecurity
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	// 此处只贴出了与sessionRegistry()相关的代码,其余配置还请自行在网上搜索。
	
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .sessionManagement()
                 // 无效session跳转
                 .invalidSessionUrl("/login")
                 .maximumSessions(1)
                 // session过期跳转
                 .expiredUrl("/login")
                 .sessionRegistry(sessionRegistry());
    }

    /**
     * 解决session失效后 sessionRegistry中session没有同步失效的问题,启用并发session控制,首先需要在配置中增加下面监听器
     * @return
     */
    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }
    
 	 /**
     * 注册bean sessionRegistry 
     */
    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }
}

3. 获取在线登录用户数量的方法

	/**
     * 获取系统在线用户数量
     * @return
     */
	public Integer getOnlineUserNum(SessionRegistry sessionRegistry){
        List<String> list = sessionRegistry.getAllPrincipals().stream()
                .filter(u -> !sessionRegistry.getAllSessions(u, false).isEmpty())
                .map(Object::toString)
                .collect(Collectors.toList());
        return list.size();
    }

4. 移除登出用户的session

import com.cebon.cdjcy.common.config.IApplicationConfig;
import com.cebon.cdjcy.common.util.IPUtils;
import com.cebon.cdjcy.common.utils.restResult.RestResult;
import com.cebon.cdjcy.common.utils.restResult.ResultCode;
import com.cebon.cdjcy.log.domain.SysLog;
import com.cebon.cdjcy.log.service.SysLogService;
import com.cebon.cdjcy.security.utils.ResponseUtils;
import com.cebon.cdjcy.sysconfig.service.SysconfigService;
import com.cebon.cdjcy.user.dto.LoginUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@Component("securityLogoutSuccessHandler")
@Slf4j
public class SecurityLogoutSuccessHandler implements LogoutSuccessHandler {
	@Autowired
	private IApplicationConfig applicationConfig;
	@Resource
	private SysconfigService sysconfigService;
	@Resource
	private SysLogService sysLogService;
	@Override
	public void onLogoutSuccess(HttpServletRequest request , HttpServletResponse response , Authentication authentication) throws IOException,
            ServletException {

		// 清除登录的session
		this.removeSesion(request);
		// 记录登出日志
        if (null != authentication) {
            this.saveLog(request, authentication);
        }
		log.info("退出成功");
		String originHeader = request.getHeader("Origin");
		ResponseUtils.addResponseHeader(response, applicationConfig.getOrigins(), originHeader);
		RestResult result = new RestResult(ResultCode.SUCCESS.getCode(),"退出成功");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(result.toJson());
		writer.flush();
	}

	/**
	 * 移除登录用户的session
	 * @param request
	 */
	private void removeSesion(HttpServletRequest request) {
		HttpSession session = request.getSession();
		// 手动让系统中的session失效 。
		session.invalidate();
	}

	/**
	 * 记录登出日志
	 * @param request
	 */
	private void saveLog(HttpServletRequest request, Authentication authentication) {
        LoginUserDTO user = (LoginUserDTO) authentication.getPrincipal();
        SysLog sysLog = new SysLog();
		sysLog.setOperation(6);
		sysLog.setLogUser(user.getId());
		sysLog.setCreateTime(new Date());
		sysLog.setLogIp(IPUtils.getIpAddr(request));
		sysLog.setLogDesc(user.getUsername() + " 退出了系统 ");
		sysLog.setLogMethod(request.getMethod());
		sysLog.setLogType(0);
		sysLogService.saveLog(sysLog);
	}
}

最后附上源码链接吧,GitHub源码地址
欢迎各位老铁star

 类似资料: