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());
}
@Bean
public SessionRegistry
sessionRegistry(){
return new SessionRegistryImpl();
}
控制器
@PreAuthorize("hasRole('管理员')")
@GetMapping("/logout/{id}")
@ResponseBody
public String
logout(@PathVariable Long id
) throws NoSuchFieldException
{
SysUser sysUser
= userService
.selectUserByUserId(id
);
List
<Object> allPrincipals
= sessionRegistry
.getAllPrincipals();
for (Object allPrincipal
: allPrincipals
) {
User user
=(User
)allPrincipal
;
if(user
.getUsername().equals(sysUser
.getLoginName())){
List
<SessionInformation> allSessions
= sessionRegistry
.getAllSessions(allPrincipal
, false);
for (SessionInformation session
: allSessions
) {
session
.expireNow();
}
}
}
return "ok";
}