springspring-bootsessionspring-security

Spring boot security: Requested url creates unwanted redis session


Lets say the login url is "/login". There are two protected resources:

When a unauthenticated user tries to access "/protected" he is being redirected to "/login". In background there is a session created, where SPRING_SECURITY_SAVED_REQUEST is stored in order to redirect user to the "/protected" url after successful login.

This is the default behaviour of spring security.

My issue: Sessions are being created even when users call "/". So all the bots and penetration tests, which call the domain without valid login information do create sessions in the underlying redis layer.

How can I prevent these sessions from being created when there is no redirect request stored or at least limit them to a defined list of valid backend endpoints?

My security configuration:

protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/password/forgot/**").permitAll()
            .antMatchers("/password/reset/**").permitAll()
            .antMatchers("/css/**").permitAll()
            .antMatchers("/js/**").permitAll()
            .antMatchers("/img/**").permitAll()
            .antMatchers( "/favicon.ico").permitAll()
            .antMatchers("/login").permitAll()
            .anyRequest().fullyAuthenticated();

    http
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .successHandler(authSuccessHandler)
            .and()
            .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login")
            .deleteCookies("SESSION")
            .clearAuthentication(true)
            .invalidateHttpSession(true)
            .permitAll();

    http.sessionManagement()
            .maximumSessions(1)
            .and()
            .sessionCreationPolicy(SessionCreationPolicy.NEVER);

    http.headers().frameOptions().disable();
    http.csrf().disable();
}

Solution

  • You could avoid having SPRING_SECURITY_SAVED_REQUEST created by setting NullRequestCache, but I guess that wouldn't work for your use case.

    or at least limit them to a defined list of valid backend endpoints?

    This could be done by providing a requestCache and setting the RequestMatcher -

          final HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
            requestCache.setRequestMatcher(new AntPathRequestMatcher("/**"));
    
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
                .requestCache().requestCache(requestCache)
                .and()...