/** * Prints the DN and attributes in an LDAPEntry to System.out. * This method used TreeSet to sort the attributes by name. */ public static void PrintEntry(LdapEntry entry) { /* To print an entry, * -- Loop through all the attributes * -- Loop through all the attribute values */ Console.WriteLine(entry.DN); Console.WriteLine("\tAttributes: "); LdapAttributeSet attributeSet = entry.getAttributeSet(); IEnumerator allAttributes = attributeSet.GetEnumerator(); while (allAttributes.MoveNext()) { LdapAttribute attribute = (LdapAttribute)(allAttributes.Current); string attributeName = attribute.Name; Console.WriteLine("\t\t" + attributeName); IEnumerator allValues = attribute.StringValues; if (allValues != null) { while (allValues.MoveNext()) { String Value = (String)allValues.Current; Console.WriteLine("\t\t\t" + Value); } } } return; }
/// <summary> /// Validate the passed user before retrieve any attributes /// </summary> /// <param name="user"></param> private Dictionary <string, string> GetUserAttributes(IUser user, IEnumerable <string> attributes) { if (attributes == null) { return(null); } if (user.ID == null) { throw new ArgumentException("Invalid User"); } if (user == null || user.ID == null) { throw new ArgumentException("Invalid User"); } string[] attribs = attributes.ToArray(); LdapEntry ldapUser = ForUser(AccountEnum.PRE_WINDOWS_2000_LOGON_NAME.ToAttribute(), user.ID, attribs); var sets = ldapUser.getAttributeSet(); Dictionary <string, string> RetVal = new Dictionary <string, string>(); foreach (var item in attributes) { RetVal.Add(item, sets.getAttribute(item)?.StringValue); } return(RetVal); }
internal static void PrintAttributes(LdapEntry entry) { foreach (LdapAttribute qs in entry.getAttributeSet()) { Console.Write(qs.Name + " => "); var size = qs.size(); if (size > 1) { var loopCount = 1; foreach (var sv in qs.StringValueArray) { if (loopCount++ == size) { Console.WriteLine(sv); } else { Console.Write(sv + ", "); } } } else { Console.WriteLine(qs.StringValue); } } }
public static void GetRootDSE(LdapConnection conn) { LdapEntry rootEntry = conn.Read(""); LdapAttributeSet attributeSet = rootEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; if (string.Equals(attributeName, "supportedCapabilities", StringComparison.InvariantCultureIgnoreCase)) { System.Console.WriteLine("Eureka"); } // string attributeVal = attribute.StringValue; foreach (string temp in attribute.StringValueArray) { string attributeVal = temp; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } // End if (!Base64.isLDIFSafe(attributeVal)) Console.WriteLine(attributeName + "value:" + attributeVal); } // Next temp } }
public string Export() { string retVal = null; if (_le == null) { return(retVal); } retVal = String.Format("dn: {0}\n", _le.DN); LdapAttributeSet las = _le.getAttributeSet(); foreach (LdapAttribute attr in las) { // FIXME: handle binary value exports; see Base64.IsLDIFSafe (attributeValue) // SupportClass.ToByteArray(attributeValue); // Base64.encode(SupportClass.ToSByteArray(byte[] from above) try { foreach (string v in attr.StringValueArray) { string tmp = v.Replace("\n", "\n "); retVal += String.Format("{0}: {1}\n", attr.Name, tmp.Trim()); } } catch {} } return(retVal); }
/// <summary> /// Loads the values of the specified properties into the property cache. /// </summary> /// <param name="propertyNames">An array of the specified properties.</param> private void LoadProperties(PropertyCollection properties, string[] propertyNames) { _inPropertiesLoading = true; try { LdapSearchResults lsc = conn.Search(Fdn, LdapConnection.SCOPE_BASE, "objectClass=*", propertyNames, false); if (lsc.hasMore()) { LdapEntry nextEntry = lsc.next(); string [] lowcasePropertyNames = null; int length = 0; if (propertyNames != null) { length = propertyNames.Length; lowcasePropertyNames = new string [length]; for (int i = 0; i < length; i++) { lowcasePropertyNames [i] = propertyNames [i].ToLower(); } } foreach (LdapAttribute attribute in nextEntry.getAttributeSet()) { string attributeName = attribute.Name; if ((propertyNames == null) || (Array.IndexOf(lowcasePropertyNames, attributeName.ToLower()) != -1)) { properties [attributeName].Value = null; properties [attributeName].AddRange(attribute.StringValueArray); properties [attributeName].Mbit = false; } } } } finally { _inPropertiesLoading = false; } }
public static void AssertSameAs(this LdapEntry expectedEntry, LdapEntry actualEntry) { Assert.Equal(expectedEntry.DN, actualEntry.DN); var expectedAttributes = expectedEntry.getAttributeSet(); var actualAttributes = actualEntry.getAttributeSet(); expectedAttributes.AssertSameAs(actualAttributes); }
public static void Print(LdapEntry entry) { Console.WriteLine($"DN: {entry.DN}"); foreach (LdapAttribute attr in entry.getAttributeSet()) { Console.WriteLine($"{attr.Name}: {attr.StringValue}"); } }
public void userList() { string LDAP_server = "localhost"; int ldapPort = 1920; string loginON = "uid=admin,ou=system"; string password = "******"; string searchBase = "ou=user,o=Company"; string searchFilter = "ObjectClass=UserLogin,Password,Name,TelNo,Email"; try { LdapConnection conn = new LdapConnection(); Console.WriteLine("Connecting to " + LDAP_server); conn.Connect(LDAP_server, ldapPort); conn.Bind(loginON, password); string[] requiredAttri = { "cn", "sn", "uid" }; LdapSearchResults result = conn.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, requiredAttri, false); while (result.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = result.next(); } catch (LdapException ex) { Console.WriteLine("LDAPconnection error:" + ex.LdapErrorMessage); continue; } Console.WriteLine("\n" + nextEntry.DN); LdapAttributeSet ldapattri = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = ldapattri.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attri = (LdapAttribute)ienum.Current; string attriName = attri.Name; string attriVal = attri.StringValue; Console.WriteLine("\t" + attriName + "\tValue = \t" + attriVal); } } conn.Disconnect(); } catch (LdapException ex) { Console.WriteLine("LDAPconnection error:" + ex.LdapErrorMessage); return; } catch (Exception ex) { Console.WriteLine("LDAPconnection error:" + ex.Message); return; } }
static void DoSearch(string ldapHost, int ldapPort, string loginDN, string password, string searchBase, string searchFilter) { try { LdapConnection conn = new LdapConnection(); Console.WriteLine("Connecting to:" + ldapHost); conn.Connect(ldapHost, ldapPort); conn.Bind(loginDN, password); LdapSearchResults lsc = conn.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, null, false); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); // Exception is thrown, go for next entry continue; } Console.WriteLine("\n" + nextEntry.DN); LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } Console.WriteLine(attributeName + "value:" + attributeVal); } } conn.Disconnect(); } catch (LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); return; } catch (Exception e) { Console.WriteLine("Error:" + e.Message); return; } }
private string IsUserExistsLDAP(string name, string pwd) { // Metemos los valores de configuración para conectarnos al ldap de Everis. int LdapPort = LdapConnection.DEFAULT_PORT; //int searchScope = LdapConnection.SCOPE_ONE; int LdapVersion = LdapConnection.Ldap_V3; //bool attributeOnly=true; String[] attrs = { LdapConnection.NO_ATTRS }; LdapConnection lc = new LdapConnection(); string resultado = ""; // Vamos a meter una restricción de tiempo. LdapSearchConstraints constraints = new LdapSearchConstraints(); constraints.TimeLimit = 10000; // ms try{ // Nos conectamos al servidor. lc.Connect(ldapHost, LdapPort); // Accedemos con las credenciales del usuario para ver si está. lc.Bind(LdapVersion, Configuration["connectionStrings:LDAPDomain"] + name, pwd); // Set values to search string base1 = "OU=Spain,OU=Europe,OU=Everis,DC=usersad,DC=everis,DC=int"; string[] attributes = new string[] { "displayName", "samaccountname" }; string filter = String.Format("(&(objectClass=user)(samaccountname={0}))", name); LdapSearchQueue lsc = lc.Search(base1, LdapConnection.SCOPE_SUB, filter, attributes, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage msg; if ((msg = lsc.getResponse()) != null) { if (msg is LdapSearchResult) { LdapEntry nextEntry = ((LdapSearchResult)msg).Entry; LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); Console.WriteLine("Nombre corto: " + attributeSet.getAttribute("samaccountname").StringValue); Console.WriteLine("Nombre Largo: " + attributeSet.getAttribute("displayName").StringValue); string[] ss = attributeSet.getAttribute("displayName").StringValue.Split(' '); string s2 = ss[0]; if (ss.Length > 1) { s2 += " " + ss[1]; } return(s2); } } lc.Disconnect(); } catch (LdapException e) { Console.WriteLine(e.Message); return(null); } catch (Exception) { Console.WriteLine("error"); return(null); } return(resultado); }
public ActionResult <HashSet <object> > GetUsersWithActiveDirectory([FromBody] SampekeyUserAccountRequest value) { var users = new HashSet <object>(); try { using (var connection = new LdapConnection { SecureSocketLayer = false }) { var _domain = Environment.GetEnvironmentVariable("AD_DDOMAIN"); var _domainServer = Environment.GetEnvironmentVariable("AD_DDOMAIN_SSERVER"); var _port = Environment.GetEnvironmentVariable("AD_PORT"); connection.Connect(_domainServer, int.Parse(_port)); connection.Bind($"{value.UserName}@{_domain}", value.Password); LdapSearchResults searchResults = connection.Search( Environment.GetEnvironmentVariable("BIND_DN"), LdapConnection.SCOPE_SUB, Environment.GetEnvironmentVariable("LDAP_FILTER"), null, false ); while (searchResults.hasMore()) { LdapEntry nextEntry = null; nextEntry = searchResults.next(); nextEntry.getAttributeSet(); var attr = nextEntry.getAttribute("mail"); if (attr == null) { users.Add(nextEntry.getAttribute("distinguishedName").StringValue); } else { users.Add(new{ Email = nextEntry.getAttribute("mail").StringValue, UserName = nextEntry.getAttribute("sAMAccountName").StringValue }); } } return(users); } } catch { return(users); } /* * HashSet<string> data = account.GetUsersWithActiveDirectory(value); * return Ok(data); */ }
public AuthenticationResult AuthenticateUser(Credentials userInfo) { AuthenticationResult result = new AuthenticationResult(); try { LdapConnection conn = new LdapConnection(); conn.Connect(_LDAPConnectionInfo.Host, _LDAPConnectionInfo.Port); conn.Bind(userInfo.Username, userInfo.Password); string profileName = null; try { LdapSearchResults lsc = conn.Search(string.Empty, LdapConnection.SCOPE_SUB, "cn = " + userInfo.Username, null, false); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException) { continue; } LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); LdapAttribute attribute = attributeSet.Cast <LdapAttribute>().Where(att => att.Name.Trim().ToUpper() == "PROFILE_NAME").SingleOrDefault(); if (attribute != null) { profileName = attribute.StringValue; } break; } } catch { } conn.Disconnect(); result.IsSuccess = true; result.UserProfile = new UserProfile(); result.UserProfile.Name = (profileName == null ? userInfo.Username : profileName); } catch (LdapException ex) { _logger.LogCritical(EventIds.AuthenticateUser, ex, nameof(LdapException)); result.ErrorMessage = ex.Message; result.IsSuccess = false; } catch (Exception ex) { _logger.LogCritical(EventIds.AuthenticateUser, ex, nameof(Exception)); result.ErrorMessage = ex.Message; result.IsServerError = true; result.IsSuccess = false; } return(result); }
// Maps all sent LDAP Properties of the user into a Dictionary public static Dictionary <string, string> GetLdapUser(string ldapUid) { try { LdapConnection conn = new LdapConnection(); conn.Connect(LdapHost, LdapPort); var lsc = conn.Search("ou=People,dc=fh-augsburg,dc=de", LdapConnection.SCOPE_ONE, $"uid={ldapUid}", null, false); var newDict = new Dictionary <string, string>(); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); // Exception is thrown, go for next entry continue; } LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } newDict.Add(attributeName, attributeVal); } } conn.Disconnect(); return(newDict); } catch (LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); return(null); } catch (Exception e) { Console.WriteLine("Error:" + e.Message); return(null); } }
protected string[] GetValues(string name) { var attributeSet = LdapEntry.getAttributeSet(); var attribute = attributeSet.getAttribute(name); String[] values = new String[0]; if (attribute != null) { values = attribute.StringValueArray; } return(values); }
public static LdapUser FromEntry(LdapEntry entry) { var attributes = entry.getAttributeSet(); var iter = attributes.GetEnumerator(); var user = new LdapUser(); while (iter.MoveNext()) { var attribute = (LdapAttribute)iter.Current; var attributeName = attribute.Name.ToUpper(); var values = attribute.StringValueArray; switch (attributeName) { case "UID": user.Uid = values[0]; break; case "CN": user.Name = values[0]; break; case "MAIL": user.Email = values[0]; break; case "NIP": user.Nip = values[0]; break; case "NRP": user.Nim = values[0]; break; case "OBJECTCLASS": foreach (var v in values) { switch (v) { case "student": user.TipeAkun = TipeAkunLdap.Student; break; case "tendik": user.TipeAkun = TipeAkunLdap.Tendik; break; //case "dosen": // user.TipeAkun = TipeAkunLdap.Dosen; // break; } } break; } } return(user); }
public IActionResult GetUsersLdap() { //Listas que utilizare para almacenar los usuarios de Ldap y sus respectivos atributos List <String> ldapusers = new List <String>(); List <String> atributos = new List <String>(); //Abrimos Socket contra el server LdapConnection ldapConn = new LdapConnection(); ldapConn.Connect("192.168.1.102", 389); //Definimos un filtro Ldap utilizado mas tarde, en este caso solo queremos los objetos tipo usuario string filter = "(ObjectClass=inetOrgPerson)"; try{ //Hacemos la busqueda LdapSearchResults query = ldapConn.Search("dc=fran,dc=local", LdapConnection.SCOPE_SUB, filter, null, false); //Recorremos la colecion de objetos Ldap while (query.hasMore()) { try { //Obtenemos el usuario iterado y obtenemos su DN y los metemos en la lista, hacemos lo mismo con //TODOS sus atributos(Por comodidad he hecho un toString) //En vez de recorrorerlos 1 a 1. LdapEntry nextEntry = query.next(); ldapusers.Add(nextEntry.DN); atributos.Add(nextEntry.getAttributeSet().ToString()); }catch (LdapException e) { //Si hubiera algun fallo el la obtencion del usuario iterado lo logeo y continuo Console.WriteLine("Error Entry: " + e.LdapErrorMessage); } } }catch (LdapException e) { //Si la busqueda ha fallado lo logueo y lanzo una excepcion para parar la app Console.WriteLine("Error Filtro: " + e.LdapErrorMessage); throw; } //Cargo las dos listas en la array dinamica de la vista ViewBag.ldapusers = ldapusers; ViewBag.atributos = atributos; return(View()); }
private bool checkAccess(string dnPerfil, string user, string password, LdapConnection ldap) { try { if (usuarioLdap.autenticado == false) { LdapSearchResults search = ldap.Search(dnPerfil, LdapConnection.SCOPE_SUB, null, null, false); LdapEntry entry = search.next(); LdapAttributeSet attribute = entry.getAttributeSet(); LdapAttribute attrib = attribute.getAttribute("uniquemember"); //if (attrib != null) //{ // usuarioLdap.autenticado = Array.Exists(attrib.StringValueArray, element => element.Contains(user.ToLower())); // if (usuarioLdap.autenticado) // usuarioLdap.perfil = attribute.getAttribute("cn").StringValue; // return usuarioLdap.autenticado; //} foreach (string usuario in attrib.StringValueArray) { if (usuario.Substring(3).Split(',').First().Equals(user)) { ldap.Bind(usuario, password); LdapSearchResults searchu = ldap.Search("cn=users,dc=network,dc=ctbc", LdapConnection.SCOPE_SUB, "uid=" + user, null, false); LdapEntry entryu = searchu.next(); LdapAttributeSet attributeu = entryu.getAttributeSet(); usuarioLdap.CPF = attributeu.getAttribute("CPF").StringValue; usuarioLdap.nomeAssociado = attributeu.getAttribute("DISPLAYNAME").StringValue; usuarioLdap.centroResultado = attributeu.getAttribute("DEPARTMENTNUMBER").StringValue; usuarioLdap.email = attributeu.getAttribute("MAIL").StringValue; usuarioLdap.tipo_usuario = attributeu.getAttribute("TIPOUSUARIO").StringValue; usuarioLdap.usuario = attributeu.getAttribute("CN").StringValue.ToLower(); usuarioLdap.perfil = attribute.getAttribute("cn").StringValue; usuarioLdap.autenticado = true; return(true); } } } } catch (LdapException) { throw new Exception("Usuário ou Senha Incorreta!"); } return(false); }
/// <summary> /// Search in AD for non-eRSA accounts created after a given date /// Only display selected attributes defined in _essentialProperties /// </summary> /// <param name="earliest"></param> public List <Dictionary <string, string> > Search(DateTime earliest) { string whenCreated = earliest.ToUniversalTime().ToString("yyyyMMddHHmmss.0Z"); Console.WriteLine("Local {0} to UTC {1}", earliest, whenCreated); string userFilter = HELPER.CreateFilter(whenCreated); List <Dictionary <string, string> > results = new List <Dictionary <string, string> >(); LdapSearchResults lsc = conn.Search(HELPER.SEARCH_BASE, LdapConnection.SCOPE_SUB, userFilter, HELPER.CREATION_PROPERTIES, false); int count = 0; while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); count++; } catch (LdapReferralException) { // Nothing really serious: constraints.ReferralFollowing = true this may not be needed // https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/b3u4u0n.html // https://technet.microsoft.com/en-us/library/cc978014.aspx continue; } catch (LdapException e) { Console.WriteLine("Move next error: {0}", e.ToString()); Console.WriteLine("Error message: " + e.Message); continue; } Console.WriteLine("\n" + nextEntry.DN); try { results.Add(GetProperties(nextEntry.getAttributeSet())); } catch (NullReferenceException ex) { Console.WriteLine("Not a qualified person account"); Console.WriteLine(ex.Message); } } return(results); }
private int checkUser(String loginDN, String password) { // Metemos los valores de configuración para conectarnos al ldap de Everis. int LdapPort = LdapConnection.DEFAULT_PORT; //int searchScope = LdapConnection.SCOPE_ONE; int LdapVersion = LdapConnection.Ldap_V3; //bool attributeOnly=true; String[] attrs = { LdapConnection.NO_ATTRS }; LdapConnection lc = new LdapConnection(); int resultado = 0; // Vamos a meter una restricción de tiempo. LdapSearchConstraints constraints = new LdapSearchConstraints(); constraints.TimeLimit = 10000; // ms try{ // Nos conectamos al servidor. lc.Connect(Constants.ldapHost, LdapPort); // Accedemos con las credenciales del usuario para ver si está. lc.Bind(LdapVersion, loginDN, password); // Set values to search string base1 = "OU=Spain,OU=Europe,OU=Everis,DC=usersad,DC=everis,DC=int"; string[] attributes = new string[] { "displayName", "samaccountname" }; string filter = String.Format("(&(objectClass=user)(samaccountname={0}))", loginDN.Substring(8)); LdapSearchQueue lsc = lc.Search(base1, LdapConnection.SCOPE_SUB, filter, attributes, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage msg; if ((msg = lsc.getResponse()) != null) { if (msg is LdapSearchResult) { LdapEntry nextEntry = ((LdapSearchResult)msg).Entry; LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); Console.WriteLine("Nombre corto: " + attributeSet.getAttribute("samaccountname").StringValue); Console.WriteLine("Nombre Largo: " + attributeSet.getAttribute("displayName").StringValue); } } lc.Disconnect(); } catch (LdapException e) { resultado = e.ResultCode; } catch (Exception) { resultado = -1; } return(resultado); }
// returns whether connection is e-dir or not. Also updates treeMatched with true or false depending on whether dirTreeName matches with the // tree name corresponding to connections's treeName public static bool IseDirectory(LdapConnection connection, string dirTreeName, out string treeName) { LdapAttribute attr = null; LdapEntry entry = null; bool eDirectory = false; treeName = null; LdapSearchResults lsc = connection.Search("", LdapConnection.SCOPE_BASE, "objectClass=*", null, false); while (lsc.hasMore()) { entry = null; try { entry = lsc.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); continue; } LdapAttributeSet attributeSet = entry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { attr = (LdapAttribute)ienum.Current; string attributeName = attr.Name; string attributeVal = attr.StringValue; if (String.Equals(attributeName, "directoryTreeName")) { treeName = attributeVal; } if (String.Equals(attributeVal, "Novell, Inc.") == true) { eDirectory = true; } } } return(eDirectory); }
//public LdapUser(LdapSettings ldapSettings, String userName) //{ // // in some cases with Active Directory // // we can't actually retrieve ldap entries // // we really just need to create a mojoportal user // // from the ldap user so if we can't read it, just create an ldap user // // with the properties we do have // // Active Directory allows us to bind a connection for authentication // // even if we can't query for entries // email = new LdapAttribute("email", userName + "@" + ldapSettings.Domain); // commonname = new LdapAttribute("commonname", userName); // userid = new LdapAttribute("userid", userName); //} public LdapUser(LdapEntry entry) { dn = entry.DN; LdapAttributeSet las = entry.getAttributeSet(); foreach (LdapAttribute a in las) { switch (a.Name) { case "mail": this.email = a; break; case "cn": this.commonname = a; break; case "userPassword": this.password = a; break; case "uidNumber": this.uidNumber = a; break; case "uid": this.userid = a; break; case "sAMAccountName": this.userid = a; break; case "givenName": this.firstName = a.StringValue; break; case "sn": this.lastName = a.StringValue; break; } } }
/// <summary> /// Valida si el usuario tiene el rol asignado /// </summary> /// <param name="conn">Conexion activa del lda de novell</param> /// <param name="usuario">Id de usuario a validar</param> /// <returns>Si el usuario tiene asignado el rol</returns> private bool TieneRolAbax(LdapConnection conn, String usuario) { var rolBaseDN = ConfigurationManager.AppSettings.Get("DNBaseRolLDAPNovell"); LdapSearchResults gruposAbax = conn.Search(rolBaseDN, LdapConnection.SCOPE_BASE, "objectClass=*", null, false); bool tieneRolUsuario = false; while (gruposAbax.hasMore()) { LdapEntry grupoEntry = null; try { grupoEntry = gruposAbax.next(); LdapAttributeSet attributeSet = grupoEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; if (attributeName.Equals("member")) { foreach (var miembro in attribute.StringValueArray) { if (miembro.Contains(usuario)) { tieneRolUsuario = true; break; } } } } } catch (Exception e) { continue; } } return(tieneRolUsuario); }
/// <summary> /// Converts Novell <see cref="LdapEntry"/> to a <see cref="ILdapEntity"/> /// </summary> /// <param name="entry">Novell entry</param> /// <param name="mapper">Mapper providing attribute names</param> /// <typeparam name="T">The resulting entity type</typeparam> /// <returns></returns> public static T ToLdapEntity <T>(this LdapEntry entry, LdapAttributeMapper mapper) where T : ILdapEntity { Dictionary <LdapAttributeAttribute, PropertyInfo> propertiesWithAttributes = Mappings.GetAttributes <T>(); LdapAttributeSet attributeSet = entry.getAttributeSet(); var entity = (T)FormatterServices.GetUninitializedObject(typeof(T)); foreach (var property in propertiesWithAttributes) { string attributeName = mapper.GetAttributeKey(property.Key); property.Value.SetValue(entity, attributeSet.getAttribute(attributeName).StringValue); } if (entity.DistinguishedName == null) { entity.DistinguishedName = entry.DN; } return(entity); }
private static string VerifyUser(string username, string password) { string searchBase = "ou=KSU,dc=KS,dc=mil,dc=no"; int searchScope = LdapConnection.SCOPE_SUB; string searchFilter = "(sAMAccountName=" + username + ")"; LdapConnection ldapConn = new LdapConnection(); ldapConn.Connect("ks.mil.no", 389); ldapConn.Bind("ks\\" + username, password); Console.WriteLine(ldapConn.Connected); string[] attr = { "sAMAccountName", "mail", "displayName", "department", "userPrincipalName", "title" }; LdapSearchQueue queue = ldapConn.Search(searchBase, searchScope, searchFilter, attr, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage message; StringBuilder sb = new StringBuilder(); while ((message = queue.getResponse()) != null) { if (message is LdapSearchResult) { LdapEntry entry = ((LdapSearchResult)message).Entry; // System.Console.Out.WriteLine("\n" + entry.DN); // System.Console.Out.WriteLine("\tAttributes: "); LdapAttributeSet attributeSet = entry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; sb.AppendLine(attributeName + ": " + attributeVal); } } } //Procced //While all the required entries are parsed, disconnect ldapConn.Disconnect(); return(sb.ToString()); }
public static string lookingForGroupDN(LdapConnection lc, String searchBase, string groupName) { string searchFilter = String.Concat("(&(objectCategory=Group)(cn=", groupName, "))"); string dn = ""; int searchScope = LdapConnection.SCOPE_SUB; String[] attrList = new String[] { "distinguishedName" }; LdapSearchConstraints cons = new LdapSearchConstraints(); cons.TimeLimit = 10000; try { LdapSearchResults searchResults = lc.Search(searchBase, searchScope, searchFilter, attrList, false, cons); // time out value LdapEntry nextEntry = null; if ((nextEntry = searchResults.next()) != null) { LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; dn = attribute.StringValue; } } } catch (LdapException e) { Console.WriteLine("ERROR: Cannot find the group DN {0} (Maybe wrong groupname? ) ", groupName); throw new System.Exception(e.ToString()); } return(dn); }
/// <summary>Copy a directory entry /// </summary> /// <param name="oldDN">Distinguished name of the entry to copy</param> /// <param name="newRDN">New name for entry</param> /// <param name="parentDN">Parent name</param> public void Copy(string oldDN, string newRDN, string parentDN) { string newDN = string.Format("{0},{1}", newRDN, parentDN); LdapEntry[] entry = Search(oldDN, LdapConnection.SCOPE_BASE, "objectclass=*", null); if (!(entry.Length > 0)) { return; } LdapEntry oldEntry = entry[0]; LdapAttributeSet attributeSet = new LdapAttributeSet(); foreach (LdapAttribute attr in oldEntry.getAttributeSet()) { LdapAttribute newAttr = new LdapAttribute(attr); attributeSet.Add(newAttr); } LdapEntry le = new LdapEntry(newDN, attributeSet); conn.Add(le); }
public Dictionary <string, string> GetUser(int uidnumber, bool all = false) { string filter = string.Format("(uidnumber={0})", uidnumber); string[] properties = { }; if (!all) { properties = HELPER.BASIC_PROPERTIES; } LdapSearchResults lsc = conn.Search(HELPER.SEARCH_BASE, LdapConnection.SCOPE_SUB, filter, properties, false); try { LdapEntry entry = lsc.next(); return(GetProperties(entry.getAttributeSet())); } catch (Exception e) { Console.WriteLine(e.ToString()); return(new Dictionary <string, string>()); } }
private void ProcessLdapSearchResult(LdapEntry ldapEntry, LdapAuthenticationModeModel ldapAuthenticationModeModel, List <string> resultMessages) { var ldapAttributeSet = ldapEntry.getAttributeSet(); var ienum = ldapAttributeSet.GetEnumerator(); var attributeValues = new Dictionary <string, string>(); while (ienum.MoveNext()) { var attribute = (LdapAttribute)ienum.Current; attributeValues.Add(attribute.Name, attribute.StringValue); } foreach (LdapAuthenticationModeLdapAttributeModel attributeMapping in ldapAuthenticationModeModel.LdapAttributes) { var ldapValue = string.Empty; if (!attributeValues.TryGetValue(attributeMapping.LdapField, out ldapValue)) { var message = $"LDAP attribute {attributeMapping.LdapField} not found."; logger.Info(message); resultMessages.Add(message); } } }
private static (User user, IList <TBService> tbServicesMatchingGroups) BuildUser( LdapEntry searchResult, IList <TBService> tbServices) { // TODO NTBS-1672 consider storing user guid as the key var attributes = searchResult.getAttributeSet(); var userAccountControl = Convert.ToInt32( attributes.getAttribute("userAccountControl").StringValue); var groups = GetAdGroups(attributes.getAttribute("memberOf").StringValues); var tbServicesMatchingGroups = tbServices .Where(tb => groups.Contains(tb.ServiceAdGroup)) .ToList(); var user = new User { Username = attributes.getAttribute("userPrincipalName").StringValue, GivenName = attributes.getAttribute("givenName").StringValue, FamilyName = attributes.getAttribute("sn").StringValue, DisplayName = attributes.getAttribute("displayName").StringValue, IsActive = IsUserEnabled(userAccountControl), AdGroups = string.Join(",", groups), IsCaseManager = tbServicesMatchingGroups.Any() }; return(user, tbServicesMatchingGroups); }