joshvilkul
joshvilkul

Reputation: 41

Spring Security SessionRegistry java config only

Can someone provide real working code snippet on how to get not empty SessionRegistry object in Spring Security using java config only (without any XML).

I'm using Spring Security v4.0.1.RELEASE

And what I'm tried to do:

  1. Implemented hashCode() and equals() methods in UserDetails with Apache Commons Lang:


    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this, "password", "id", "role", "description", "registrationDate", "enabled");
    }

    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj, "password", "id", "role", "description", "registrationDate", "enabled");
    }

  1. Enabled HttpSessionEventPublisher:


    public class AppSecurityInitializer extends
            AbstractSecurityWebApplicationInitializer {

        @Override
        protected boolean enableHttpSessionEventPublisher() {
            return true;
        }
    }

  1. Defined beans in security config class:


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

    @Bean
    public SessionAuthenticationStrategy getSessionAuthStrategy(SessionRegistry sessionRegistry) {
        ConcurrentSessionControlAuthenticationStrategy controlAuthenticationStrategy =
                new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry);

        return controlAuthenticationStrategy;
    }

  1. Set http security:

    httpSecurity
            .formLogin().loginPage("/login")
            .defaultSuccessUrl("/", true)
            .successHandler(new LoginSuccessHandler())
            .and()
            .sessionManagement()
            .sessionAuthenticationStrategy(sessionAuthenticationStrategy).maximumSessions(1).maxSessionsPreventsLogin(true)
            .and().and()
            .csrf().disable();
    return httpSecurity;

Code works, it's prevents me to login under the same user twise, but when I'm getting SessionRegistry in controller class, it's always empty.

Upvotes: 4

Views: 2787

Answers (1)

bgraves
bgraves

Reputation: 839

Looks as if spring creates a different SessionRegistryImpl on its own.

What about

httpSecurity
    .sessionManagement()
    .maximumSessions(1)
    .sessionRegistry(getSessionRegistry());

leaving out the sessionAuthenticationStrategy stuff?!

Upvotes: 1

Related Questions