Java oauth2和其他身份验证提供程序的WebSecurity配置程序
我的应用程序上有2种类型的用户。一种类型可以使用LDAP AuthenticationProvider,另一种类型可以使用Salesforce Oauth2。他们都需要访问我的API 我的Web安全配置适配器中有以下内容:Java oauth2和其他身份验证提供程序的WebSecurity配置程序,java,spring-boot,spring-security,Java,Spring Boot,Spring Security,我的应用程序上有2种类型的用户。一种类型可以使用LDAP AuthenticationProvider,另一种类型可以使用Salesforce Oauth2。他们都需要访问我的API 我的Web安全配置适配器中有以下内容: // Config for LDAP httpSecurity .csrf().disable().headers().frameOptions().deny() .and() .author
// 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配置,那么效果会很好
有没有一种方法可以同时使用两种身份验证解决方案来实现配置?您可以使用提供程序来为每种实现进行配置,然后向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);
}
}
在本例中,有一个CustomAuthenticationProvider,另一个是InMemoryAuthentication提供程序。您始终可以编写自己的提供者的实现
资料来源:
@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();
}
}