SpringSecurity踢出指定用户

SpringSecurity中可以使用 SessionRegistry 的实现类 SessionRegistryImpl 来获取session相关信息,可以通过这个实现类来踢出用户。

SpringSecurity配置

复制代码
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    ISysUserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/webjars/**","/asserts/**","/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/loginPost")
                .failureUrl("/login?error=true")
                .defaultSuccessUrl("/index")
                .and()
                .logout()
                .logoutUrl("/logout")
                .addLogoutHandler(new MyLogoutHandler())
                .logoutSuccessUrl("/login")
                .and()
                .rememberMe()
                .userDetailsService(userService)
                .tokenRepository(jdbcTokenRepository())
                //保存登录状态时间,单位是秒
                .tokenValiditySeconds(60*60*3)
                .and()
                //关闭请求头中的frame选项,不限制iframe
                .headers().frameOptions().disable()
                //关闭跨域
                .and().csrf().disable()
                .sessionManagement()
                //无效session跳转
                .invalidSessionUrl("/login")
                //同时登陆多个只保留一个
                .maximumSessions(1)
                //过期session跳转
                .expiredUrl("/login")
                .sessionRegistry(sessionRegistry());
    }

    /** 注册SessionRegistry*/
    @Bean
    public SessionRegistry sessionRegistry(){
        return new SessionRegistryImpl();
   	}

控制器

复制代码
/** 踢出用户 */
    @PreAuthorize("hasRole('管理员')")
    @GetMapping("/logout/{id}")
    @ResponseBody
    public String logout(@PathVariable Long id) throws NoSuchFieldException {
    	//通过id查询用户
        SysUser sysUser = userService.selectUserByUserId(id);
        //获取所有principal信息
        List<Object> allPrincipals = sessionRegistry.getAllPrincipals();
        for (Object allPrincipal : allPrincipals) {
            User user=(User)allPrincipal;
            //判断是否跟传递的id所找到的用户登录名一致
            if(user.getUsername().equals(sysUser.getLoginName())){
                List<SessionInformation> allSessions = sessionRegistry.getAllSessions(allPrincipal, false);
                for (SessionInformation session : allSessions) {
                	//使当前session过期
                    session.expireNow();
                }
            }
        }
        return "ok";
    }
相关推荐
林shir1 天前
Java基础1.4-运算符
java·开发语言
ldj20201 天前
springboot logback 设置日志级别
java·spring boot·logback
C雨后彩虹1 天前
字符串拼接
java·数据结构·算法·华为·面试
遥远_1 天前
一次高并发压垮系统的排查与重生(上)
java·微服务·性能优化·高并发·限流·qps
C雨后彩虹1 天前
ConcurrentHashMap入门:高并发场景的 HashMap替代方案
java·数据结构·哈希算法·集合·hashmap
weixin_425023001 天前
Spring boot 2.7.18使用knife4j
java·spring boot·后端
产幻少年1 天前
面试题八股
java
wanghowie1 天前
01.08 Java基础篇|设计模式深度解析
java·开发语言·设计模式
Data_agent1 天前
京东商品价格历史信息API使用指南
java·大数据·前端·数据库·python