To resolve the error "No AuthenticationProvider found for authentication.UsernamePasswordAuthenticationToken" in Spring Boot, follow these steps:
public class MyAuthenticationProvider implements AuthenticationProvider, Serializable {
@Override
public boolean supports(Class<? extends Object> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
// ...
}
Instead of excluding the entire SecurityAutoConfiguration, you can specifically exclude org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration.
Alternatively, you can expose a UserDetailsService bean that achieves the same effect, allowing you to get rid of the configureGlobal method. Here's how:
<@Bean>
public UserDetailsService userDetailsService() {
UserDetails user = User.builder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
If you create your own UserDetailsService bean, there's no need to manually define a bean for AuthenticationProvider. This is because by default, a DaoAuthenticationProvider bean will be automatically created, which will automatically pick up your defined UserDetailsService bean.
However, if you define two or more UserDetailsService beans, then you'll need to define your own AuthenticationProvider. I made a mistake because I didn't realize I had another class that implements the UserDetailsService interface and annotated it with @Service, which created a second UserDetailsService bean.