Как лишить законной силы предыдущие сессии пользователя в весенней загрузке безопасности - PullRequest
0 голосов
/ 26 декабря 2018

Я использую Spring Security, которая позволяет максимум 1 сеанс на пользователя, но проблема в том, что если пользователь забывает выйти из системы и закрывает окно браузера, и если он снова входит в систему, он получает ошибку Превышение максимального сеанса, что очевидно, яищу способ, чтобы при повторном входе в систему все старые сеансы становились недействительными и пользователь мог успешно войти в систему

Это мой SecurityConfig.java

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;
    //for handling user success handler
    @Autowired
    private CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler;
    @Override
    //this configuration is for handling user requests
    protected void configure(HttpSecurity http)  {
         try {
            http
                .authorizeRequests()
                .antMatchers("/orders").permitAll()
                .antMatchers("/createrole").permitAll()
                     .antMatchers("/login").permitAll()
                     .antMatchers("/admin/**").hasAuthority("admin")
                     .antMatchers("/agent/**").hasAuthority("agent")
                     .antMatchers("/distributor/**").hasAuthority("distributor")
                     .antMatchers("/home/**").hasAuthority("user").anyRequest()
                    .authenticated().and().csrf().disable().formLogin().successHandler(customizeAuthenticationSuccessHandler)
                    .loginPage("/login").failureUrl("/login?error=true")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .and().logout()
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/logout.done").deleteCookies("JSESSIONID")
                    .invalidateHttpSession(true) 
                    .logoutSuccessUrl("/login").and().exceptionHandling().accessDeniedPage("/403");
            http.sessionManagement( ).maximumSessions(1). maxSessionsPreventsLogin(true);
            http.sessionManagement( ).sessionFixation( ).migrateSession( )
                    .sessionAuthenticationStrategy( registerSessionAuthStr( ) );

        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("Exception here");
        }
    }


    //this method allows static resources to be neglected by spring security
    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
            .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**","/assets/**","/fonts/**","/dis/**","/vendor1/**","/assets2/**");
    }




    @Bean
    public SessionRegistry sessionRegistry( ) {
        SessionRegistry sessionRegistry = new SessionRegistryImpl( );
        return sessionRegistry;
    }
    @Bean
    public RegisterSessionAuthenticationStrategy registerSessionAuthStr( ) {
        return new RegisterSessionAuthenticationStrategy( sessionRegistry( ) );
    }
    @Bean
    public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
        return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)  {
         //BCryptPasswordEncoder encoder = passwordEncoder();
        //auth.inMemoryAuthentication().withUser("logan@yahoo.com").password(encoder.encode("admin")).roles("user");
    try {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    } catch (Exception e) {

        System.out.println("Login Failed");
    }
} 


}

// Это мой пользовательский сервис данных пользователя

@Service
public class CustomUserDetailsService implements UserDetailsService{
    @Autowired
    private UserServiceImpl userservice;

    @Autowired
    private RoleServiceImpl roleservice;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        User user=userservice.getUserByusername(username);

            if(user != null && user.isEnabled()) {
                List<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
                return buildUserForAuthentication(user, authorities);
            } 

            else {
                throw new UsernameNotFoundException("username not found");
            }

    }

    private List<GrantedAuthority> getUserAuthority(Set<Role> userRoles) {
        Set<GrantedAuthority> roles = new HashSet<>();
        userRoles.forEach((role) -> {
            roles.add(new SimpleGrantedAuthority(role.getRole()));
        });

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>(roles);
        return grantedAuthorities;
    }

    private UserDetails buildUserForAuthentication(User user, List<GrantedAuthority> authorities) {
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
    }

}

1 Ответ

0 голосов
/ 26 декабря 2018

Изменить maxSessionPreventsLogin false, так как максимальный сеанс равен 1, он сделает недействительным предыдущий сеанс, надеюсь, он будет работать

http.sessionManagement( ).maximumSessions(1). maxSessionsPreventsLogin(false);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...