除了侦听端口之外,您的服务器还必须“理解”LDAP 协议。我使用 OpenDS LDAP SDK (http://www.middleware.vt.edu/pubs/opends-sdk-0.9.0/)。
代码是这样的
public class MyLdapServer
implements ServerConnectionFactory<LDAPClientContext, Integer> {
private LDAPListener listener;
public void init() {
try {
listener = new LDAPListener(1389, this);
} catch (IOException e) {
logger.error("error opening LDAP listener", e);
}
}
public void destroy() {
listener.close();
}
@Override
public ServerConnection<Integer> handleAccept(LDAPClientContext context)
throws ErrorResultException {
if (logger.isDebugEnabled())
logger.debug("ldap connection from: " + context.getPeerAddress());
IncomingLdapConnection ilc = new IncomingLdapConnection(context);
return ilc;
}
private static Logger logger = LoggerFactory.getLogger(MyLdapServer.class);
}
IncomingLdapConnection 允许您处理 LDAP 操作:
public class IncomingLdapConnection
implements ServerConnection<Integer> {
public void handleBind(Integer ctx, int version, BindRequest request,
ResultHandler<? super BindResult> resultHandler,
IntermediateResponseHandler intermediateResponseHandler)
throws UnsupportedOperationException {
if (request.getAuthenticationType() != -128) {
logger.warn("LDAP BIND: unsupported authentication type: " + request.getAuthenticationType());
resultHandler.handleResult(Responses.newBindResult(ResultCode.AUTH_METHOD_NOT_SUPPORTED));
return;
}
String bindName = request.getName();
if (bindName.length() > 0) {
if (request instanceof GenericBindRequest) {
GenericBindRequest bindRequest = (GenericBindRequest)request;
String userName = parseUidDn(bindName);
if (userName == null) {
// manche LDAP-Clients senden keine DN, sondern direkt den Namen
userName = bindName;
}
String password = bindRequest.getAuthenticationValue().toString();
logger.debug("LDAP BIND: non-anonymous bind, user = " + userName);
anonymous = false;
} else {
logger.warn("LDAP BIND: non-anonymous bind, but unsupported request");
resultHandler.handleResult(Responses.newBindResult(ResultCode.AUTH_METHOD_NOT_SUPPORTED));
return;
}
} else {
logger.debug("LDAP BIND: anonymous bind");
anonymous = true;
}
boolean success = anonymous;
if (!anonymous) {
// authenticate user, set "success"
}
if (success)
resultHandler.handleResult(Responses.newBindResult(ResultCode.SUCCESS));
else
resultHandler.handleResult(Responses.newBindResult(ResultCode.INVALID_CREDENTIALS));
authenticated = success;
}
编辑:用于回答 LDAP 搜索请求的 OpenDS 代码
public void handleSearch(Integer ctx, SearchRequest request,
SearchResultHandler responseHandler, IntermediateResponseHandler intermediateResponseHandler)
throws UnsupportedOperationException {
if (request.getScope() == SearchScope.BASE_OBJECT && request.getName().isRootDN()) {
logger.debug("LDAP Search: BASE_OBJECT");
responseHandler.handleEntry(Responses.newSearchResultEntry(rootEntry));
} else {
// do the search
// parameters: request.getName(), request.getScope(), request.getFilter()
}
responseHandler.handleResult(Responses.newResult(ResultCode.SUCCESS));
}