Spring Security | What Is Spring Security? | Java Configuration

Spring Security 3.2 supports Java Configuration introduced in Spring 3.1. It provides namespace-equivalent settings without XML and improves compile-time checks and refactoring.

Replacing Hello World with Java Configuration

Configure web.xml to use AnnotationConfigWebApplicationContext instead of XmlWebApplicationContext.

<context-param>
    <param-name>contextClass</param-name>
    <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>sample.spring.security.MySpringSecurityConfig</param-value>
</context-param>

Implementing the Container

@EnableWebSecurity
public class MySpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin();
    }

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("devkuma").password("1234").roles("USER");
    }
}

Enabling Spring Security

Annotate the class loaded by AnnotationConfigWebApplicationContext with @EnableWebSecurity. The annotation imports WebSecurityConfiguration and enables global authentication.

Configuring Spring Security

Extend WebSecurityConfigurerAdapter and override methods such as configure(HttpSecurity). HttpSecurity corresponds to the XML <http> namespace element.

  • authorizeRequests() begins URL authorization settings.
  • and() returns HttpSecurity and continues the method chain.
  • formLogin() enables form authentication.

The example is equivalent to:

<sec:http>
    <sec:intercept-url pattern="/login" access="permitAll" />
    <sec:intercept-url pattern="/**" access="isAuthenticated()" />
    <sec:form-login />
    <sec:logout />
</sec:http>

Configuring User Information

AuthenticationManagerBuilder helps define an AuthenticationManager and supports method chaining for UserDetailsService. You can also define a Bean directly.

@Bean
public UserDetailsService userDetailsService() {
    InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
    manager.createUser(User.withUsername("hoge").password("HOGE").roles("USER").build());
    return manager;
}