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";
    }
相关推荐
Suxing929 分钟前
C语言基础分享:从“租房”到“拆迁”,C语言动态内存管理
java·数据结构·算法
减瓦30 分钟前
别让 Java 版本选择变成生产事故
java
ikun_文31 分钟前
Java集合框架Collection拓展进阶
java·java ee
码匠许师傅44 分钟前
【C++ 面试真题】聊聊 C++ 的虚函数和多态
java·c++·面试
chuan.bai1 小时前
Java RAG 实战(第 8 篇):Spring Boot RAG 查询 API
java·spring boot·贪心算法
FlyWIHTSKY1 小时前
idea中集成claude功能
java·ide·人工智能·intellij-idea·cloudera
Java成神之路-1 小时前
Spring AI 统一结构化返回:ChatModel / ChatClient 两种实现方式
java·springaialibaba
Mr. zhihao1 小时前
深度解析:为什么Java序列化需要搭配ByteArrayOutputStream?IO装饰器模式的精妙设计
java·开发语言·装饰器模式
存在morning1 小时前
【Python 开发实践 一】Python vs Go vs Java 三门语言对比
java·python·golang
vx-程序开发2 小时前
springboot旅游推介平台---附源码24175
java·spring boot·python·spring cloud·eclipse·django·idea