springboot+security 动态权限修改session立即失效(六)

来源:互联网 发布:机器人编程语言py 编辑:程序博客网 时间:2024/06/07 03:24

这个是springboot结合security 系列的第六篇博客了,不知不觉已经写了6篇了。中间有写的很不好,不尽人意。文章的排列也是我遇见问题,解决问题的过程,希望大家见谅。

这不,最近出现了这个问题, 一个管理员A登录后,在进行操作,此时管理员B 修改了管理员A 的权限,将管理员A 修改为普通用户,但此时管理员A,需要重新登录权限修改才会起效,但是管理员A此时没有退出登录,还可以进行操作,这就是很危险的问题了。

为了解决这个问题,需要修改管理员A 的权限的时候将管理员A的session 置为无效,强制其登录。

解决思路:

我门都知道当用户登录以后security 会把生成的session 放到 SessionRegistry 里面。那么我门想让session 失效只用找到对应的session,然后将它从SessionRegistry 中剔除出去就好了。

但是查看了源码发现SessionRegistry 是 final 。。。。。这个可怎么办呢?

自己new 一个对象吧,所以我就new SessionRegistry(),并用我自己的SessionRegistry管理session 咯

做法如下:

1. 新配置一个bean

 @Bean    public SessionRegistry getSessionRegistry(){        SessionRegistry sessionRegistry=new SessionRegistryImpl();        return sessionRegistry;    }

2. 修改WebSecurityConfig

然后在WebSecurityConfig的configure(HttpSecurity http) 方法中添加session管理

 @Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {    @Autowired    private UrlUserService urlUserService;    @Autowired    SessionRegistry sessionRegistry;    @Override    protected void configure(HttpSecurity http) throws Exception {        http                .csrf().disable()                .authorizeRequests()                .antMatchers("/login").permitAll()                .antMatchers("/logout").permitAll()                .antMatchers("/images/**").permitAll()                .antMatchers("/js/**").permitAll()                .antMatchers("/css/**").permitAll()                .antMatchers("/fonts/**").permitAll()                .antMatchers("/favicon.ico").permitAll()                .antMatchers("/").permitAll()                .anyRequest().authenticated()                .and()                .sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry)                .and()                .and()                .logout()                .and()                .httpBasic();    }   }

3. 使session失效

此时已经完成了一大半了。
只用在修改用户的方法里判断有没有修改用户的权限,如果有修改用户的权限就使session失效。
session失效代码如下:

private void invalidateSession(User user){        List<Object> o= sessionRegistry.getAllPrincipals();        for (Object principal : o) {            if (principal instanceof User) {                final User loggedUser = (User) principal;                if (user.getUsername().equals(loggedUser.getUsername())) {                    List<SessionInformation> sessionsInfo = sessionRegistry.getAllSessions(principal, false);                    if (null != sessionsInfo && sessionsInfo.size() > 0) {                        for (SessionInformation sessionInformation : sessionsInfo) {                            sessionInformation.expireNow();                        }                    }                }            }        }    }

本文代码稍后会提交到 :https://github.com/527515025/springBoot

1 0
原创粉丝点击