You can use Providers to for each of your implementation and then register this provider with Spring AuthenticationManager.
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
//Implementaton for Authentication
}
@Override
public boolean supports(Class<?> auth) {
return auth.equals(UsernamePasswordAuthenticationToken.class);
}
}
Now in your WebSecurityConfigurerAdapter, you can register multiple auth providers
@EnableWebSecurity
public class MultipleAuthProvidersSecurityConfig
extends WebSecurityConfigurerAdapter {
@Autowired
CustomAuthenticationProvider customAuthProvider;
@Override
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(customAuthProvider);
auth.inMemoryAuthentication()
.withUser("memuser")
.password(encoder().encode("pass"))
.roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/api/**")
.authenticated();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Here in this example, there is one CustomAuthenticationProver and other is InMemoryAuthentication provider. You could always write implementations of your own providers.
Source: https://www.baeldung.com/spring-security-multiple-auth-providers
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…