Mic*_*elB 2 java spring ldap active-directory spring-boot
我对 LDAP 几乎一无所知,对 spring 安全性更不了解,但我正在尝试配置一个 spring 启动应用程序以针对 ldap 实例进行身份验证,但我被卡住了。
我在 adldap.company.com 上获得了 ldap 服务器名称和 dc=ad,dc=company,dc=com 的基本 dn
我有一些 Python 代码可以进行简单的绑定并且可以工作。
LDAP_USERNAME = 'username@ad.company.com'
LDAP_PASSWORD = 'password'
base_dn = 'dc=ad,dc=company,dc=com' # not used for bind I guess, only search
try:
ldap_client = ldap.initialize('ldap://adldap.company.com')
ldap_client.set_option(ldap.OPT_REFERRALS,0)
ldap_client.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)
except ldap.INVALID_CREDENTIALS as e:
ldap_client.unbind()
return 'Wrong username and password: %s' % e
except ldap.SERVER_DOWN:
return 'AD server not available'
Run Code Online (Sandbox Code Playgroud)
如果我运行此代码,它似乎成功绑定为“username@ad.company.com”和密码“password”。
我还有一个我认为应该处理身份验证的 WebSecurityConfig 类:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/secure")
.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and()
.httpBasic();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDnPatterns("uid={0}")
.contextSource()
.url("ldap://adldap.company.com");
//.url("ldap://adldap.company.com/dc=ad,dc=company,dc=com");
}
}
Run Code Online (Sandbox Code Playgroud)
当我在应用程序中转到 /secure 时,会弹出一个基本的身份验证,但随后我尝试输入的任何内容都会得到 401 Unauthorized。我试过“username@ad.company.com”,没有域,把这些东西放在 userDnPatterns 中,比如 {0}@adldap.company.com 和一堆其他东西。我曾尝试使用不同的 URL 并在其中使用基本 dn。似乎没有任何效果。我错过了什么?
另外,这是对用户进行身份验证的正确方法吗?我已经阅读了有关绑定身份验证以及有关绑定和搜索的内容,但服务器不允许匿名绑定,所以我想我需要某种可以绑定和执行搜索的“应用程序用户”,对吗?那个更好吗”?
Active Directory 有其自己的非标准用户身份验证语法,这与通常的 LDAP DN 绑定不同。
Spring Security 为 Active Directory 提供了一个专门的 AuthenticationProvider。
尝试这个 :
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/secure")
.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider());
}
@Bean
public AuthenticationManager authenticationManager() {
return new ProviderManager(Arrays.asList(activeDirectoryLdapAuthenticationProvider()));
}
@Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider("adldap.company.com", "ldap://adldap.company.com");
provider.setConvertSubErrorCodesToExceptions(true);
provider.setUseAuthenticationRequestCredentials(true);
return provider;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8042 次 |
| 最近记录: |