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";
    }
相关推荐
Laurence2 分钟前
Qt 前后端通信(QWebChannel Js / C++ 互操作):原理、示例、步骤解说
前端·javascript·c++·后端·交互·qwebchannel·互操作
Pu_Nine_96 分钟前
JavaScript 字符串与数组核心方法详解
前端·javascript·ecmascript
码云数智-园园13 分钟前
从输入 URL 到页面展示:一场精密的互联网交响乐
前端
2501_9159184129 分钟前
苹果App Store上架审核卡住原因分析与解决方案指南
android·ios·小程序·https·uni-app·iphone·webview
架构师沉默32 分钟前
Java 终于有自己的 AI Agent 框架了?
java·后端·架构
skiy39 分钟前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
秋水无痕39 分钟前
# 手把手教你从零搭建 AI 对话系统 - React + Spring Boot 实战(一)
前端·后端
高桥凉介发量惊人41 分钟前
基础与工程篇-多环境配置(dev/test/prod)与打包策略
前端
墨鱼笔记42 分钟前
前端必看:Vite.config.js 最全配置指南 + 实战案例
前端·vite
kyriewen43 分钟前
异步编程:从“回调地狱”到“async/await”的救赎之路
前端·javascript·面试