Spring MVC 4 Global Basic HTTP Authentication

328 views Asked by At

I need to set up global basic HTTP authentication for a staging server. Nothing fancy. I just want to require username/password to access anything. I also would like to use only Java config. I've experimented with a lot of different solutions, but none of them working. I'm always able to access all resources on the server. This is what I'm doing now:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
    System.out.println("Configuring HttpSecurity");

    http
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .httpBasic();
   }

   @Autowired
   public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    System.out.println("Configuring global AuthenticationManagerBuilder");

    auth
            .inMemoryAuthentication()
            .withUser("user").password("password").roles("USER");
   }
}

I can see in the logs that these snippets are being executed. As you can see, in the first method, I am requiring that all requests are authenticated. In the second method, I am specifying in memory authentication.

1

There are 1 answers

0
Abhinav Rai On

Your SOP statements are getting printed (while container instantiation) because of @Configuration (which is again not required as it is also declared by @EnableWebSecurity). You still need to register the spring security filter chain in your web.xml or MVC initializer class that extends WebMvcConfigurerAdapter or implements WebApplicationInitializer if you wish to use it with the application filter chain. For example (java config as you are looking for the same):

EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(
            DispatcherType.REQUEST, DispatcherType.ERROR);
container.addFilter("springSecurityFilterChain",
            DelegatingFilterProxy.class).addMappingForUrlPatterns(
            dispatcherTypes, false, "/*");

where container is an instance of ServletContext.