Search code examples
spring-securitycluster-computingspring-session

Spring session stored over DB + Spring security authentication, clustered enviroment


I have one application over spring 4, with spring security to the authentication, and spring session to share session on clustered enviroment.

I was implement the sessionRepository from Spring Session to store the session on the database, so when I enter to the site spring session create a cookie named "SESSION" and store it on the DB.

The idea of this session-DB implementation is here:

How can I do relational database-based HTTP Session Persistence in Spring 4?

At this moment I have one cookie "SESSION". When I login on the site spring security creates another cookie "JSESSION" but this is not stored in the DB, and this cookie have the "authentication info".

My question is: this implementation is correct for clustered enviroment? or I need to make another modification?

Thanks in advance.

EDIT 2:

I recently test my app, I and make one mistake over my explanation, when I enter to the site I have one cookie "SESSION" even if I login the "SESSION" cookie stills, but there is no another cookie, if I clean the session table and refresh the site the user is loggedoff. This is the correct behavior?

EDIT:

Here is my "configure" from SecurityConfig (extend from WebSecurityConfigurerAdapter).

@Override
protected void configure(final HttpSecurity http) throws Exception {
    // @formatter:off
    http
        //.csrf().disable()
        .authorizeRequests()
        .antMatchers(
                "/login*",
                "/logout*",
                "/forgotPassword*",
                "/user/initResetPassword*",
                "/user/resetPassword*",
                "/admin/saveConfiguration",
                "/resources/**"
        ).permitAll()
        .antMatchers("/invalidSession*").anonymous()
        .anyRequest().authenticated()
    .and()
        .formLogin()
        .loginPage("/login.html")
        .loginProcessingUrl("/login")
        .defaultSuccessUrl("/homepage.html")
        .failureUrl("/login.html?error=true")
        .successHandler(myAuthenticationSuccessHandler)
        .usernameParameter("username")
        .passwordParameter("password")
        .permitAll()
    .and()
        .addFilterBefore(this.sessionSessionRepositoryFilter, ChannelProcessingFilter.class)
        .sessionManagement()
        .invalidSessionUrl("/login.html")
        .sessionFixation()
        .migrateSession()
    .and()
        .logout()
        .invalidateHttpSession(false)
        .logoutUrl("/vu_logout")
        .logoutSuccessUrl("/logout.html?ls=true")
        .deleteCookies("JSESSION")
        .logoutSuccessHandler(mySimpleUrlLogoutSuccessHandler)
        .permitAll();
    // @formatter:on
}

Here my login success handler:

@Component("myAuthenticationSuccessHandler")
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());

private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    handle(request, response, authentication);
    HttpSession session = request.getSession(false);

    if (session != null) {
        session.setMaxInactiveInterval(60 * 10);
    }
    clearAuthenticationAttributes(request);
}

protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    String targetUrl = determineTargetUrl(authentication);

    if (response.isCommitted()) {
        return;
    }

    redirectStrategy.sendRedirect(request, response, targetUrl);
}

protected String determineTargetUrl(Authentication authentication) {
    boolean isUser = false;
    boolean isAdmin = false;
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority grantedAuthority : authorities) {
        if (grantedAuthority.getAuthority().equals("OPER") || grantedAuthority.getAuthority().equals("AUDITOR")) {
            isUser = true;
        } else if (grantedAuthority.getAuthority().equals("ADMIN")) {
            isAdmin = true;
            isUser = false;
            break;
        }
    }

    if(isUser || isAdmin)
    {
        return "/home.html";
    }
    else
    {
        throw new IllegalStateException();
    }
}

protected void clearAuthenticationAttributes(HttpServletRequest request) {
    HttpSession session = request.getSession(false);
    if (session == null) {
        return;
    }
    session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}

public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
    this.redirectStrategy = redirectStrategy;
}

protected RedirectStrategy getRedirectStrategy() {
    return redirectStrategy;
}

}


Solution

  • After a few days on research and testing this implementation is correct to work over clustered enviroment.

    If anyone need a sample project Mati has one over your github repository: https://github.com/Mati20041/spring-session-jpa-repository