我想编写自己的 LDAP 身份验证提供程序。我正在扩展AbstractUserDetailsAuthenticationProvider
,其中有一个方法retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
。
我想重写这个方法并编写我自己的数据检索方法。如何在 Java 中做到这一点?如何进行 LDAP 查询以及如何连接到 LDAP 服务器?我在互联网上搜索,但没有找到任何帮助。
编辑:22.01.2013
@Override
protected UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
LdapUser userDetail = null;
log.entry("retrieveUser", authentication.getPrincipal());
UsernamePasswordAuthenticationToken userToken = authentication;
String userName = userToken.getName();
userName = userName != null ? userName.toLowerCase() : userName;
String password = userToken.getCredentials().toString();
try {
if (password == null || "".equals(password)) {
log.debug("retrieveUser", "no password provided");
throw new AuthenticationCredentialsNotFoundException(
"Invalid login or password");
}
}
catch (AuthenticationCredentialsNotFoundException e) {
log.debug("retrieveUser", "no password provided");
}
// connection with ldap and check retrieved username and password
connect = connection(userName, password);
if (connect) {
log.debug("retrieve user", "correct connection with ldap");
userDetail = new LdapUser();
setUserDetails(userDetail, ctx, username);
} else {
log.error("retrieve user", "Failed connection");
}
log.exit("retrieveUser", "user logged: " + userDetail);
return userDetail;
}
我的 security.xml 文件
<http auto-config='true'>
<intercept-url pattern="/**/*.ico" filters="none" />
<intercept-url pattern="/**/*.gif" filters="none" />
<intercept-url pattern="/**/*.jpg" filters="none" />
<intercept-url pattern="/**/*.css" filters="none" />
<intercept-url pattern="/**/*.js" filters="none" />
<intercept-url pattern="/**/*.png" filters="none" />
<intercept-url pattern="/logout.jsp*" filters="none" />
<intercept-url pattern="/index.jsp*" filters="none" />
<intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN" />
<logout logout-success-url="/index.jsp"/>
<form-login login-page="/index.jsp"
authentication-failure-url="/error_ldap.jsp"
default-target-url="/main_ldap.jsp" always-use-default-target="true" />
</http>
<authentication-manager>
<authentication-provider ref="ldapAuthenticationProvider">
<password-encoder hash="sha" />
</authentication-provider>
</authentication-manager>
登录成功后,我重定向到 main_ldap.jsp,但如果身份验证失败,我收到此错误。我试图抛出异常 UsernameNotFoundException 而不是在retrieveUser 方法中返回null(这是不允许的)但是发生了任何事情(只有我得到了这个异常)。