The common way to configure Spring Security is by extending WebSecurityConfigurerAdapter
and annotating with @Configuration
. e.g., from the Java docs:
@Configuration
class SimpleSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin()
.and()
.logout().deleteCookies("remove").invalidateHttpSession(false)
.logoutUrl("/custom-logout").logoutSuccessUrl("/logout-success");
}
}
If you need to have multiple configurations, for instance, for different paths, then you can either http.antMatchers(...)
, or you can provide multiple configurations. But these achieve different things, and this distinction needs to be understood.
Each WebSecurityConfigurerAdapter
sets up a filter chain, which is in turn used by the FilterChainProxy
. This will have a set of filters which add authentication, authorisation, and whatever other checks and rewrites that are configured.
When you use an http.antMatchers(...)
within a configuration it simply narrows the path of the authorisation processing, until the next and()
which will ten return the original HttpSecurity
object. It simply makes chaining the calls together easier, but in a lot of cases, it makes it more confusing.
The HttpSecurity
object can however, set a base antMatcher(...)
that determines if the filter chain applies.
http.antMatcher("/api/**").csrf().disable();
In order to use multiple filters, it is important to understand how they are matched. The FilterChainProxy
will go through each filter chain in order, and will apply the first one that matches based on the antMatcher(...)
. This means that:
- You can not have multiple filter chains that match the same path, and
- Any default filter chain must be last.
Use the @Order(1)
annotation to set the order, ordered from lowest number to highest number. If this is excluded then the default is to match last.
Finally, each filter chain has its own AuthenticationManager
which is accessed using the authenticationManager()
method.
Summary
- Each
WebSecurityConfigurerAdapter
is a filter chain, with its own set of filters and rules, - The first filter chain matching the path to the
antSelector(...)
will be used, orderd byOrder(1)
, - The
antMatchers(...)
can be used to apply authorisation to a specific path, - The
and()
method returns theHttpSecurity
object for that filter chain, - There is one
AuthenticationManager
per filter chain.