我的应用有两种类型的用户。一种可以使用 LDAP AuthenticationProvider,另一种可以使用 Salesforce Oauth2。他们都需要访问我的 API。
我的 WebSecurityConfigurerAdapter 中有以下内容:
// Config for LDAP
httpSecurity
.csrf().disable().headers().frameOptions().deny()
.and()
.authorizeRequests().antMatchers("/admin/login").permitAll().
antMatchers("/admin/**").authenticated()
.and().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
// Config for Salesforce Oauth2
httpSecurity.csrf().disable().headers().frameOptions().deny().and().
authorizeRequests().antMatchers("/client/**").authenticated()
.and()
.oauth2Login()
.userInfoEndpoint()
.userService(myOAuth2UserService);
我以为我可以在同一个 WebConf 中同时使用这两个配置,但它没有按预期工作,因为当我调用 /client 时出现错误 401。但如果我删除了第一个 LDAP 配置,它会工作得很好。>
有没有办法用两种身份验证解决方案来实现配置?
答案 0 :(得分:1)
您可以为每个实现使用提供程序,然后使用 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);
}
}
现在在您的 WebSecurityConfigurerAdapter 中,您可以注册多个身份验证提供程序
@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();
}
}
在此示例中,有一个 CustomAuthenticationProver,另一个是 InMemoryAuthentication 提供程序。您始终可以编写自己的提供程序的实现。
来源:https://www.baeldung.com/spring-security-multiple-auth-providers