Resolved: Spring Security 5+: Obtaining an AuthenticationManager without having to build HttpSecurity

In this post, we will see how to resolve Spring Security 5+: Obtaining an AuthenticationManager without having to build HttpSecurity

Question:

Java 11 and Spring Security 2.7.x here. I am trying to upgrade my config away from the (deprecated) WebSecurityConfigurerAdapter-based implementation to one using SecurityFilterChain.
What’s important about my implementation is that I have the ability to define and configure/wire up my own:
  • Authentication Filter (UsernamePasswordAuthenticationFilter impl)
  • Authorization Filter (BasicAuthenticationFilter impl)
  • Custom authentication error handler (AuthenticationEntryPoint impl)
  • Custom authorization error handler (AccessDeniedHandler impl)

Here’s my current setup based on reading a bunch of blogs and articles:
When I start up my app I am getting:
The Google Gods say this is because I’m calling httpSecurity.build() twice which is not allowed. However:
  • My authn and authz filter require an AuthenticationManager instance; and
  • It seems that the only way (please tell me if I’m wrong!) to get an AuthenticationManager instance is to run httpSecurity.build(); but
  • I need the authn/authz filter before I can call httpSecurity.build()

Can anyone help nudge me across the finish line here? Thanks for any and all help!

Best Answer:

We are doing something like:
Since instance of AuthenticationManager is required in runtime only, that is enough to pass supplier to filter during configuration phase
UPD.
Well, now it is clear why you need a reference to AuthenticationManager.
First option:
In case of ApiAuthorizationFilter you are actually do not need to extend BasicAuthenticationFilter – just let spring-security to do it’s job and enable basic authentication via httpSecurity.httpBasic(). For ApiAuthenticationFilter it is possible to pass AuthenticationManagerResolver or Supplier<AuthenticationManager> to it:
Second option
Write your own implementation of AbstractHttpConfigurer, should look like:

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com