{
LdapSession ldapSession = getLdapSession();
CoreSession adminSession = getAdminSession();
DirectoryService directoryService = adminSession.getDirectoryService();
LdapServer ldapServer = ldapSession.getLdapServer();
OperationManager operationManager = directoryService.getOperationManager();
// first, we have to find the entries which has the uid value
EqualityNode<String> filter = new EqualityNode<String>(
directoryService.getSchemaManager().getAttributeType( SchemaConstants.UID_AT ), new StringValue( user ) );
SearchOperationContext searchContext = new SearchOperationContext( directoryService.getAdminSession() );
searchContext.setDn( directoryService.getDnFactory().create( ldapServer.getSearchBaseDn() ) );
searchContext.setScope( SearchScope.SUBTREE );
searchContext.setFilter( filter );
searchContext.setNoAttributes( true );
EntryFilteringCursor cursor = operationManager.search( searchContext );
Exception bindException = new LdapAuthenticationException( "Cannot authenticate user uid=" + user );
while ( cursor.next() )
{
Entry entry = cursor.get();
try
{
BindOperationContext bindContext = new BindOperationContext( ldapSession.getCoreSession() );
bindContext.setDn( entry.getDn() );
bindContext.setCredentials( Strings.getBytesUtf8( password ) );
bindContext.setIoSession( ldapSession.getIoSession() );
bindContext.setInterceptors( directoryService.getInterceptors( OperationEnum.BIND ) );
operationManager.bind( bindContext );
cursor.close();
return bindContext.getSession();
}