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";
    }
相关推荐
q***766636 分钟前
SpringSecurity 实现token 认证
android·前端·后端
llxxyy卢37 分钟前
xss-maps(1-12)尝试思路过关加源码分析
前端·xss
川白40 分钟前
为防在家摸鱼,用计网知识实践屏蔽B站!
后端
小璞41 分钟前
一、React Fiber 架构与任务调度详解
前端·react.js·前端框架
小璞41 分钟前
四、虚拟 DOM 与 Diff 算法:架构设计的智慧
前端·react.js·前端框架
南蓝42 分钟前
【AI 日记】调用大模型的时候如何按照 sse 格式输出
前端·人工智能
Chejdj42 分钟前
ViewModel#onCleared的实现原理
android·源码阅读
一树论44 分钟前
浏览器插件开发经验分享二:如何处理日期控件
前端·javascript
小璞44 分钟前
六、React 并发模式:让应用"感觉"更快的架构智慧
前端·react.js·架构