Home > Net >  Can't use any kind of SessionListener when using Spring Security in Spring Boot
Can't use any kind of SessionListener when using Spring Security in Spring Boot

Time:11-30

I have a very basic Spring Security setup using Session. My problem is that I can't find a way to use any kind of Session Listener (both Spring and Servlet API versions) to listen to SessionCreated event. Login is working and session is being created properly.

The reason I need a listener is because I want to initialize certain session attributes (ex. shopping kart, recent items list) so I can access them seamlessly from @Controller request mappings, without having to worry whether session attributes are initialized.

Security configuration code:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
                .and()
                .authorizeRequests()
                .antMatchers("/secured/**").authenticated()
                .anyRequest().permitAll()
                .and()
                .formLogin()
                .loginPage("/login")
                .and()
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/")
                .and()
                .rememberMe().key("unique");
    }

    ...
}

First, I have tried the most basic session listenter:

@Component
public class InitHttpSessionListener implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        ...
    }
}

I have also tried answers from here, which also didn't work

CodePudding user response:

As what was getting clear from your comments is that you are using Spring Session JDBC. Due to the nature of JDBC this doesn't support publishing of session events and thus you cannot listen to those events.

As a workaround you could create your own AuthenticationSuccessHandler and put the logic for filling the Session in there. Or listen to an AuthenticationSuccessEvent using a Spring event listener (would be a bit harder to get to the session but doable).

  • Related