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";
    }
相关推荐
goyeer2 分钟前
【Kubernetes】Kubernetes之CRI详解
java·容器·kubernetes
牧瀬クリスだ7 分钟前
从零手写博客系统:分层架构与统一响应(一)
java·数据库·架构·mybatis·springboot·安全架构
Rain的Java大神之路1 小时前
LeetCode 40 组合总和 II:面试官想听的不是回溯,而是那行去重代码
java·leetcode·面试
wno7042 小时前
Centos下PostgreSQL安装部署详细步骤
java·数据库·spring boot
nice_lcj5202 小时前
【从零理解计算机网络 · 04】TCP 三次握手:为什么恰好是三次
java·后端·tcp/ip·计算机网络·面试·tcp·三次握手
Sarvartha3 小时前
反射综合案例:SQL 语句生成
java·开发语言
Resean022313 小时前
Spring 源码分析(二)配置类的解析与扫描
java·后端·spring
小毛球.13 小时前
第 3 篇:IDEA 最新版下载与完整安装教程(Mac)
java·macos·intellij-idea·idea
Misnearch15 小时前
ScheduledExecutorService
java·线程池
ashiho16 小时前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口