HttpSecurity, WebSecurity and AuthenticationManagerBuilder

user3488241 picture user3488241 · Apr 10, 2014 · Viewed 23.7k times · Source

Could anyone explain when to override configure(HttpSecurity), configure(WebSecurity) and configure(AuthenticationManagerBuilder)?

Answer

Nick Vasic picture Nick Vasic · Feb 2, 2015

configure(AuthenticationManagerBuilder) is used to establish an authentication mechanism by allowing AuthenticationProviders to be added easily: e.g. The following defines the in-memory authentication with the in-built 'user' and 'admin' logins.

public void configure(AuthenticationManagerBuilder auth) {
    auth
        .inMemoryAuthentication()
        .withUser("user")
        .password("password")
        .roles("USER")
    .and()
        .withUser("admin")
        .password("password")
        .roles("ADMIN","USER");
}

configure(HttpSecurity) allows configuration of web based security at a resource level, based on a selection match - e.g. The example below restricts the URLs that start with /admin/ to users that have ADMIN role, and declares that any other URLs need to be successfully authenticated.

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/admin/**").hasRole("ADMIN")
        .anyRequest().authenticated()
}

configure(WebSecurity) is used for configuration settings that impact global security (ignore resources, set debug mode, reject requests by implementing a custom firewall definition). For example, the following method would cause any request that starts with /resources/ to be ignored for authentication purposes.

public void configure(WebSecurity web) throws Exception {
    web
        .ignoring()
        .antMatchers("/resources/**");
}

You can refer to the following link for more information Spring Security Java Config Preview: Web Security