Spring add authentication manager to filter

Viewed 50

How to configure spring to use AuthenticationManager with my custom implementation of UserDetailService in http basic authentication?

I tried this:

@Bean
public SecurityFilterChain configure(HttpSecurity http, PasswordEncoder bCryptPasswordEncoder) throws Exception {
    AuthenticationManager authManager = http.getSharedObject(AuthenticationManagerBuilder.class)
            .userDetailsService(new UserDetailServiceImpl(userManager))
            .passwordEncoder(bCryptPasswordEncoder)
            .and()
            .authenticationProvider(new DaoAuthenticationProvider()).build();
    http.httpBasic().configure(http.authenticationManager(authManager));
    return http.build();
}

But the BasicAuthentication filter does not register the authManager.

I could do something like:

 BasicAuthenticationFilter filter = new BasicAuthenticationFilter(authManager);
 http.addFilter(filter);

But there might be a different, more standard way to do it.

1 Answers

Okay apparently no need to configure authentication manager. For basic authentication it's enough to provide UserDetailService like so:

    @Bean
    public SecurityFilterChain configureFilterChain(HttpSecurity http) throws Exception {
       return http.authorizeHttpRequests().anyRequest().authenticated()
                .and().httpBasic().authenticationEntryPoint(bookieAuthenticationEntryPoint)
                .and().userDetailsService(new UserDetailServiceImpl(userManager))
                .formLogin().disable()
                .and().build() 
Related