Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between registering an authenticationprovider with HttpSecurity vs AuthenticationManagerBuilder in Spring Security?

Tags:

WebSecurityConfigurerAdapter offers two overrides as follows:

protected void configure(AuthenticationManagerBuilder auth)

and

protected void configure(HttpSecurity http)

Both HttpSecurity and AuthenticationManagerBuilder offer registration for authenticationProviders. Is there any difference between registering my providers with one vs the other?

I'm also using Spring boot 2.1 with @SpringBootApplication(exclude = SecurityAutoConfiguration.class) to turn off their autoconfig completely.

like image 692
Jazzepi Avatar asked Nov 21 '18 02:11

Jazzepi


1 Answers

From Spring Security Architecture

The main strategy interface for authentication is AuthenticationManager [...]

The most commonly used implementation of AuthenticationManager is ProviderManager, which delegates to a chain of AuthenticationProvider instances. An AuthenticationProvider is a bit like an AuthenticationManager [...]

A ProviderManager can support multiple different authentication mechanisms in the same application by delegating to a chain of AuthenticationProviders. If a ProviderManager doesn’t recognise a particular Authentication instance type it will be skipped.

A ProviderManager has an optional parent, which it can consult if all providers return null. If the parent is not available then a null Authentication results in an AuthenticationException.

enter image description here

Generally speaking WebSecurityConfigurerAdapter provides configuration for HttpSecurity apart from Filter's configuration (like UsernamePasswordAuthenticationFilter, LogoutFilter etc.) it's also creates and configures (adding AuthenticationProviders and parent AuthenticationManager) AuthenticationManagers in HttpSecurity by using AuthenticationManagerBuilder.

WebSecurityConfigurerAdapter will create only one AuthenticationManager for HttpSecurity. However AuthenticationManager has its own AuthenticationProviders and its own optional parent AuthenticationProvider. When you are doing http.authenticationProvider(...) you are adding new AuthenticationProvider to the AuthenticationManager which belong to that http. By using configure(AuthenticationManagerBuilder auth) you are configuring AuthenticationManager which is the parent of the AuthenticationManager which belongs to that particular HttpSecurity.

Spring is providing default configuration for the parent of that particular AuthenticationManager, but by using configure(AuthenticationManagerBuilder auth) you are rejecting spring's configuration in favour of your (auth).

like image 191
Andrew Sasha Avatar answered Oct 11 '22 02:10

Andrew Sasha