我的要求是。我有一个具有弹簧安全性的登录页面。首先,我想用活动目录验证用户名和密码,如果用户存在,那么我只需要检查数据库中的用户名。
我已尝试使用spring security在线进行LDAP身份验证..但我无法确切地找到如何实现这一点..任何身体都可以帮助...
答案 0 :(得分:1)
您需要做的是注入LdapAuthenticator的自定义实现。我已经做了类似的事情,但是在一个旧项目中,3年后你可能不得不改变代码。基本上我们做这样的事情(仔细阅读评论):
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
import org.springframework.security.ldap.authentication.LdapAuthenticator;
public class LdapAuthenticatorImpl implements LdapAuthenticator {
private DefaultSpringSecurityContextSource contextFactory;
private String principalPrefix = "";
public DirContextOperations authenticate(Authentication authentication) {
// Grab the username and password out of the authentication object.
String principal = principalPrefix + authentication.getName();
String password = "";
if (authentication.getCredentials() != null) {
password = authentication.getCredentials().toString();
}
// If we have a valid username and password, try to authenticate.
if (!("".equals(principal.trim())) && !("".equals(password.trim()))) {
InitialLdapContext ldapContext = (InitialLdapContext) contextFactory.getReadWriteContext();
//We attempt the super class authentication which will validate the credentials. In case
//of success it will return an instance of authAdapter otherwise it will throw BadCredentialsException.
DirContextOperations authAdapter = super.authenticate(authentication) ;
//We can consider authentication successful with LDAP.
//TODO check the user in the database
//
return authAdapter;
} else {
throw new BadCredentialsException("Blank username and/or password!");
}
}
}
在配置文件中,您需要使用您的实现覆盖名为ldapAuthenticator的现有bean。以下示例使用grails语法,但您可以在application-descriptor.xml中执行相同的操作:
ldapAuthenticator(CustomBindAuthenticator, ref('contextSource')) {
userSearch = ref('ldapUserSearch')
}
您也可以在xml中配置它,如下所示:
<bean id="ldapAuthenticator" class="com.mypackage.myClass">
<constructor-arg ref="contextSource"/>
<property name="userSearch" ref="ldapUserSearch"/>
</bean>