当前位置: 首页 > article >正文

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";
    }

http://www.kler.cn/a/565876.html

相关文章:

  • 【AIGC系列】5:视频生成模型数据处理和预训练流程介绍(Sora、MovieGen、HunyuanVideo)
  • SpringBoot 3.0微服务架构实战:从设计到部署
  • 【Blender】三、材质篇--3.4 凹凸感和置换形变
  • 如何使用useEffect模拟组件的生命周期?
  • Opencv 阈值与平滑处理
  • API网关相关知识点
  • 深度学习开源数据集大全:从入门到前沿
  • [文献阅读] DCEC - Deep Clustering with Convolutional Autoencoders
  • 在ubuntu 24.04.2 通过 Kubeadm 安装 Kubernetes v1.31.6
  • Web1、Web2 与 Web3 的核心区别
  • 钉钉宜搭智能车辆管理系统:AIoT与低代码融合的数字化解决方案
  • 可编辑73页PPT | DeepSeek自学手册-从理论模型训练到实践模型应用
  • 数据结构——位图
  • 使用自动化运维工具 Ansible 集中化管理服务器
  • 记录深度学习中有用的终端命令
  • java23种设计模式-责任链模式
  • 【VSCode】VSCode下载安装与配置极简描述
  • HTTP学习——————(四)TLS等加密算法
  • 力扣——最小路径和
  • [自然语言处理]pytorch概述--什么是张量(Tensor)和基本操作