user10127693
user10127693

Reputation:

How to invalidate previous sessions of user in spring boot security

I am using spring security that allows maximum 1 session per user ,but the problem is if the user forgets to logout and closes the browser window and if he logins again ,he gets error of Maximum session exceeded which is obvious,I am looking for a way such that if users login again all the old session invalidate and user can successfully login

This is my 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("[email protected]").password(encoder.encode("admin")).roles("user");
    try {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    } catch (Exception e) {

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


}

//This is my Custom user details Service

@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);
    }

}

Upvotes: 2

Views: 3889

Answers (1)

Shubham Dixit
Shubham Dixit

Reputation: 1

Change maxSessionPreventsLogin false ,as maximum session is 1 it will invalidate previous session ,hope it will work

http.sessionManagement( ).maximumSessions(1). maxSessionsPreventsLogin(false);

Upvotes: 3

Related Questions