Herr Derb
Herr Derb

Reputation: 5357

Spring Security Configuration is not getting applied

I'm working on a Spring project. The functionality is already done. What's missing is the security context. As my project (maven) is separated in different sub projects (Services, RestControllers, Domain), I want the security configuration to be a separate sub project as well, which I only have to add as dependency to the main app to activate it.

I started with a very basic configuration, which is, by now, the only class in the security sub project:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
        .withUser("admin")
        .password("admin1")
        .roles("ADMIN", "USER");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/").permitAll().and().authorizeRequests().anyRequest().authenticated();
    }
}

As soon as I add this project as dependency to my main app, the security context is obviously getting activated, as the default spring login dialogue pops up. The thing is, that Spring ignores the configuration which I've defined in the SecurityConfiguration. It even won't let me access '/', or neither it let's me login with the defined user. Checking in debug mode, it never runs through the public void configure(AuthenticationManagerBuilder auth) method.

In a nut shell: It activates the spring security context, but it does not apply my configuration. Why is that?

Upvotes: 1

Views: 1635

Answers (1)

micaro
micaro

Reputation: 976

In case of Spring MVC project with Java based configuration import SecurityConfiguration to your ApplicationConfiguration

@EnableWebMvc
@Configuration
@ComponentScan({"xx.xxx.xx.*"})
@PropertySource("classpath:xxx.properties")
@Import(value = {SecurityConfiguration.class}) // <= like this
public class ApplicationConfiguration extends WebMvcConfigurerAdapter { ... }

You may also need SecurityInitializer. This class has to be present even though it's empty. This is a good place for certain filters that must be executed before security configuration.

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer { }

Upvotes: 1

Related Questions