difference between overriding configure(AuthentiationManageraBuilder) method vs just creating a DaoAuthenticationProvider

Viewed 221

I'm trying out Spring Security Authentication using JPA. and I came across two youtube channels (Java Brains) and (Telusko). Java Brains guy has overridden the configure(AuthenticationManagerBuilder Auth) method from WebSecurityConfigurer and the Telusko guy had used a bean for setting up DaoAuthenticationProvider to configure userDetailService. I know that authenticationManager calls authenticationProvider which inturn calls userDetailService to load users. correct if I'm wrong. can somebody explain whats is the difference between these two approaches under the hood. Thanks in advance.

1 Answers

The difference is one way of authentication (DaoAuthenticationProvider) vs opening to more choices (AuthenticationManagerBuilder). By configuring DaoAuthenticationProvider, means you choose the "Dao"/"userDetailService" to authenticate your users. Spring Security uses Authentication Manager for Authentication, and ProviderManager is the default authentication manager, which iterates an Authentication request through a list of AuthenticationProviders. And DaoAuthenticationProvider is one of them.

By configuring the authentication manger with method: configure(AuthenticationManagerBuilder Auth) You have more flexibility, you can configure the authentication manager to use your customized Authentication Provider. (and you CustomAuthenticationProvider implements AuthenticationProvider interface)

    @Autowired
    private CustomAuthenticationProvider customAuthProvider;

    @Override
    public void configure(AuthenticationManagerBuilder auth)  {
        auth.authenticationProvider(customAuthProvider);
    }

And you can also configure the DaoAuthenticationProvider by simply provide a userdetailservice, as the AuthenticationManagerBuilder will wire it up.

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

with that said, using AuthenticationManagerBuilder is much more common, as it can be used for configuring different kinds of authentication providers.

Related