我有Spring Boot 2 REST应用程序,并且我想配置Spring Security以支持对相同资源(例如/员工)的Google登录或LDAP身份验证
我已经通过httpBasic(连接到Apache AD LDAP服务器)进行了身份验证。
我还通过Google OAuth2登录设置了身份验证。 这两种配置都可以分别正确地工作(我可以通过Google登录进行身份验证,但不能同时使用LDAP进行身份验证,因为我必须重新配置弹簧安全性),现在,我需要能够通过这两种方式进行身份验证同时。
我的LDAP身份验证的Spring Security配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/", "/login**","/callback/", "/webjars/**", "/error**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.ldapAuthoritiesPopulator(customLdapAuthoritiesPopulator)
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource()
.url(env.getProperty("spring.ldap.urls") + env.getProperty("spring.ldap.base"))
.and()
.passwordCompare()
.passwordAttribute("userPassword")
.passwordEncoder(new LdapShaPasswordEncoder());
}
这是我为Google OAuth2登录重新配置Spring Security时的外观
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/", "/login**","/callback/", "/webjars/**", "/error**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.userInfoEndpoint().oidcUserService(customOAuth2UserService);
}
我需要的结果:用户有两个选择:无论哪种方式,都可以使用Oauth2进行身份验证,或者使用httpBasic LDAP进行身份验证。
我认为有一种方法可以配置Spring Security,以便OAuth2和httpBasic LDAP可以协同工作,但是我不知道该怎么做。
答案 0 :(得分:0)
有可能。
基本身份验证使用基本身份验证,其中oauth将承载用作标题授权标头的一部分。
我们可以使用自定义请求匹配器来检测基本身份验证并通过ldap进行身份验证。如果没有,它将通过oauth流过。
首先,将WebSecurityConfigurerAdapter的级别设置为高于Oauth身份验证服务器,
@Configuration
@Order(2)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
使用我们的自定义请求映射器,
http
.csrf()
.disable()
.requestMatcher(new BasicRequestMatcher())
.authorizeRequests()
.antMatchers("/", "/login**","/callback/", "/webjars/**", "/error**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
自定义请求匹配项,
private static class BasicRequestMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest request) {
String auth = request.getHeader("Authorization");
return (auth != null && auth.startsWith("Basic"));
}