Beispiel #1
0
 protected LdapEntryBase(LdapAttributeSet attributeSet)
 {
     ObjectCategory    = attributeSet.getAttribute("objectCategory")?.StringValue;
     ObjectClass       = attributeSet.getAttribute("objectClass")?.StringValueArray;
     Name              = attributeSet.getAttribute("name")?.StringValue;
     CommonName        = attributeSet.getAttribute("cn")?.StringValue;
     DistinguishedName = attributeSet.getAttribute("distinguishedName")?.StringValue;
 }
Beispiel #2
0
 public LdapUser(LdapAttributeSet attributeSet) : base(attributeSet)
 {
     SamAccountName    = attributeSet.getAttribute("sAMAccountName")?.StringValue;
     UserPrincipalName = attributeSet.getAttribute("userPrincipalName")?.StringValue;
     DisplayName       = attributeSet.getAttribute("displayName")?.StringValue;
     Email             = attributeSet.getAttribute("mail")?.StringValue;
     Phone             = attributeSet.getAttribute("telephoneNumber")?.StringValue;
 }
        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);
        }
Beispiel #4
0
        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);
        }
Beispiel #5
0
        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);
        }
 private Identity.Models.LdapEntry CreateEntryFromAttributes(string distinguishedName, LdapAttributeSet attributeSet)
 {
     return(new Identity.Models.LdapEntry
     {
         ObjectSid = attributeSet.getAttribute("objectSid")?.StringValue,
         ObjectGuid = attributeSet.getAttribute("objectGUID")?.StringValue,
         ObjectCategory = attributeSet.getAttribute("objectCategory")?.StringValue,
         ObjectClass = attributeSet.getAttribute("objectClass")?.StringValue,
         CommonName = attributeSet.getAttribute("cn")?.StringValue,
         Name = attributeSet.getAttribute("name")?.StringValue,
         DistinguishedName = attributeSet.getAttribute("distinguishedName")?.StringValue ?? distinguishedName,
         SamAccountName = attributeSet.getAttribute("sAMAccountName")?.StringValue,
         SamAccountType = int.Parse(attributeSet.getAttribute("sAMAccountType")?.StringValue ?? "0"),
     });
 }
Beispiel #7
0
        public void Ldap_Attribute_Set_Attribute_Should_Be_Taken_By_Name()
        {
            var attrName = "objectclass";
            LdapAttributeSet attributeSet = new LdapAttributeSet();
            var attr = new LdapAttribute(attrName, "inetOrgPerson");

            attributeSet.Add(attr);
            var attrFromContainer = attributeSet.getAttribute(attrName);

            Assert.Equal(attrName, attrFromContainer.Name);
        }
Beispiel #8
0
 public static void AssertSameAs(this LdapAttributeSet expectedAttributeSet, LdapAttributeSet actualAttributeSet, List <string> excludeAttributes)
 {
     Assert.Equal(expectedAttributeSet.Count, actualAttributeSet.Count);
     foreach (LdapAttribute expectedAttribute in expectedAttributeSet)
     {
         if (excludeAttributes.Contains(expectedAttribute.Name))
         {
             continue;
         }
         var actualAttribute = actualAttributeSet.getAttribute(expectedAttribute.Name);
         expectedAttribute.ByteValues.ShouldBeEquivalentTo(actualAttribute.ByteValues);
     }
 }
Beispiel #9
0
 public static DomainUserDto Adapt(LdapAttributeSet attributeSet)
 {
     return(new DomainUserDto
     {
         Login = attributeSet.getAttribute(LoginAttribute).StringValue,
         FirstName = attributeSet.getAttribute(GivenNameAttribute).StringValue,
         LastName = attributeSet.getAttribute(SNAttribute).StringValue,
         DisplayName = attributeSet.getAttribute(DisplayNameAttribute).StringValue,
         Email = attributeSet.getAttribute(MailAttribute).StringValue,
         PhoneNumber = attributeSet.getAttribute(TelephoneNumberAttribute).StringValue,
         UserPricipalName = attributeSet.getAttribute(UserPrincipalNameAttribute).StringValue,
     });
 }
Beispiel #10
0
        public void Ldap_Attribute_Set_Should_Be_Cloned()
        {
            var attrName = "objectclass";
            LdapAttributeSet attributeSet = new LdapAttributeSet();
            var attr = new LdapAttribute(attrName, "inetOrgPerson");

            attributeSet.Add(attr);

            var attributeSetClone = (LdapAttributeSet)attributeSet.Clone();

            bool equals = attributeSet == attributeSetClone;

            Assert.False(equals);

            var  attrFromContainer      = attributeSet.getAttribute(attrName);
            var  attrFromCloneContainer = attributeSetClone.getAttribute(attrName);
            bool equalsAttrs            = attrFromContainer == attrFromCloneContainer;

            Assert.True(equalsAttrs);
        }
Beispiel #11
0
        /// <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);
        }
Beispiel #12
0
        /// <summary>
        /// Convert ResultPropertyCollection to Dictionary
        /// </summary>
        /// <param name="searchResult">SearchResult</param>
        /// <returns>Dictionary</returns>
        private static Dictionary <string, string> GetProperties(LdapAttributeSet searchResult)
        {
            if (searchResult == null)
            {
                return(null);
            }

            Dictionary <string, string> filtered = new Dictionary <string, string>();

            // Our checking logic depends on uidnumber
            if (searchResult.getAttribute("uidnumber") == null)
            {
                throw new NullReferenceException(string.Format("{0} has no uidnumber", searchResult.getAttribute("cn")));
            }

            foreach (LdapAttribute attribute in searchResult)
            {
                Console.WriteLine(attribute.Name.ToLower() + " = " + attribute.StringValue);
                filtered[attribute.Name.ToLower()] = attribute.StringValue;
            }

            return(filtered);
        }
Beispiel #13
0
        public static IEnumerable <Change> ToChangesAdd(this LdapAttributeSet set, string dn, string changedBy)
        {
            List <Change> changes     = new List <Change>();
            var           objectClass = set.getAttribute(LdapProperties.ObjectClass).StringValue;
            var           guid        = Guid.NewGuid();

            foreach (LdapAttribute attr in set)
            {
                changes.AddRange(attr.StringValueArray.Select(val => new Change
                {
                    Dn   = dn,
                    Type = attr.Name == LdapProperties.CommonName
                        ? Change.TypeEnum.Created
                        : Change.TypeEnum.CreatedAttribute,
                    ObjectClass   = objectClass,
                    Property      = attr.Name,
                    NewValue      = attr.Name == LdapProperties.UserPassword ? "****" : attr.StringValue,
                    ChangeContext = guid,
                    ChangedBy     = changedBy,
                }));
            }

            return(changes);
        }
Beispiel #14
0
        private LdapUser CreateUserFromAttributes(string distinguishedName, LdapAttributeSet attributeSet)
        {
            var ldapUser = new LdapUser
            {
                //ObjectSid = attributeSet.getAttribute("objectSid")?.StringValue,
                //ObjectGuid = attributeSet.getAttribute("objectGUID")?.StringValue,
                //ObjectCategory = attributeSet.getAttribute("objectCategory")?.StringValue,
                //ObjectClass = attributeSet.getAttribute("objectClass")?.StringValue,
                //IsDomainAdmin = attributeSet.getAttribute("memberOf") != null && attributeSet.getAttribute("memberOf").StringValueArray.Contains("CN=Domain Admins," + this._ldapSettings.SearchBase),
                //MemberOf = attributeSet.getAttribute("memberOf")?.StringValueArray,
                //CommonName = attributeSet.getAttribute("cn")?.StringValue,
                FullName = attributeSet.getAttribute("name")?.StringValue,
                UserName = attributeSet.getAttribute("sAMAccountName")?.StringValue,
                //UserPrincipalName = attributeSet.getAttribute("userPrincipalName")?.StringValue,
                //Name = attributeSet.getAttribute("name")?.StringValue,
                //DistinguishedName = attributeSet.getAttribute("distinguishedName")?.StringValue ?? distinguishedName,
                //DisplayName = attributeSet.getAttribute("displayName")?.StringValue,
                FirstName = attributeSet.getAttribute("givenName")?.StringValue,
                LastName  = attributeSet.getAttribute("sn")?.StringValue,
                //Description = attributeSet.getAttribute("description")?.StringValue,
                Phone = attributeSet.getAttribute("telephoneNumber")?.StringValue,
                Email = attributeSet.getAttribute("mail")?.StringValue,
                //Address = new LdapAddress
                //{
                //    Street = attributeSet.getAttribute("streetAddress")?.StringValue,
                //    City = attributeSet.getAttribute("l")?.StringValue,
                //    PostalCode = attributeSet.getAttribute("postalCode")?.StringValue,
                //    StateName = attributeSet.getAttribute("st")?.StringValue,
                //    CountryName = attributeSet.getAttribute("co")?.StringValue,
                //    CountryCode = attributeSet.getAttribute("c")?.StringValue
                //},

                //SamAccountType = int.Parse(attributeSet.getAttribute("sAMAccountType")?.StringValue ?? "0"),
            };

            //ldapUser.Id = ldapUser.SamAccountName;

            return(ldapUser);
        }
        private THUMember CreateUserFromAttributes(string distinguishedName, LdapAttributeSet attributeSet)
        {
            var ldapUser = new THUMember
            {
                ObjectSid         = attributeSet.getAttribute("objectSid")?.StringValue,
                ObjectGuid        = attributeSet.getAttribute("objectGUID")?.StringValue,
                ObjectCategory    = attributeSet.getAttribute("objectCategory")?.StringValue,
                ObjectClass       = attributeSet.getAttribute("objectClass")?.StringValue,
                MemberOf          = attributeSet.getAttribute("memberOf")?.StringValueArray.ToList(),
                CommonName        = attributeSet.getAttribute("cn")?.StringValue,
                UserName          = attributeSet.getAttribute("name")?.StringValue,
                Name              = attributeSet.getAttribute("name")?.StringValue,
                DistinguishedName = attributeSet.getAttribute("distinguishedName")?.StringValue ?? distinguishedName,
                DisplayName       = attributeSet.getAttribute("displayName")?.StringValue,
                Email             = attributeSet.getAttribute("mail")?.StringValue
            };


            return(ldapUser);
        }
        public IEnumerable <ActiveDirectoryUser> QueryActiveDirectory(string username)
        {
            List <ActiveDirectoryUser> listToReturn = new List <ActiveDirectoryUser>();

            try
            {
                using (var cn = new LdapConnection())
                {
                    cn.Connect(options.Host, options.Port);      //connect
                    cn.Bind(options.Username, options.Password); // bind with credentials
                    LdapSearchResults lsc = cn.Search("dc=supergrp,dc=net",
                                                      LdapConnection.SCOPE_SUB,
                                                      "(&(objectClass=person)(sAMAccountName=*" + username + "*))",
                                                      null,
                                                      false);

                    while (lsc.hasMore())
                    {
                        LdapEntry nextEntry = null;
                        try
                        {
                            nextEntry = lsc.next();
                            LdapAttributeSet attributeSet = nextEntry.getAttributeSet();
                            var newActiveDirectoryUser    = new ActiveDirectoryUser();

                            // addition check to be in place because our Ad has computers also setup as Users and Persons
                            if (attributeSet.getAttribute("givenName") == null)
                            {
                                continue;
                            }

                            newActiveDirectoryUser.Firstname = attributeSet.getAttribute("givenName").StringValue;

                            if (attributeSet.getAttribute("sn") != null)
                            {
                                newActiveDirectoryUser.Lastname = attributeSet.getAttribute("sn").StringValue;
                            }

                            if (attributeSet.getAttribute("sAMAccountName") != null)
                            {
                                newActiveDirectoryUser.UserName = attributeSet.getAttribute("sAMAccountName").StringValue;
                            }

                            if (attributeSet.getAttribute("mail") != null)
                            {
                                newActiveDirectoryUser.Email = attributeSet.getAttribute("mail").StringValue;
                            }

                            listToReturn.Add(newActiveDirectoryUser);
                        }
                        catch (LdapException)
                        {
                            // Exception is thrown, return the list
                            return(listToReturn);
                        }
                    }
                }
            }
            catch (System.Exception)
            {
                return(listToReturn);
            }

            return(listToReturn);
        }
Beispiel #17
0
        /// <summary>
        /// Retrieves group information from ldap
        /// </summary>
        /// <param name="retrieveGroupMembers">true to return users in each group. This may hurt performance</param>
        /// <param name="optionalGroupName">Group to lookup by name. Null for all groups</param>
        /// <returns></returns>
        public XDoc GetGroupInfo(bool retrieveGroupMembers, string optionalGroupName)
        {
            LdapConnection conn      = null;
            XDoc           resultXml = null;

            try {
                //Confirm a query bind has been established
                conn = Bind();

                string searchFilter;

                //Build the searchfilter based on if a group name is given.
                if (!string.IsNullOrEmpty(optionalGroupName))
                {
                    optionalGroupName = EscapeLdapString(optionalGroupName);

                    //Looking up group by name
                    searchFilter = string.Format(PhpUtil.ConvertToFormatString(_config.GroupQuery), optionalGroupName);
                }
                else
                {
                    //Looking up all groups
                    searchFilter = _config.GroupQueryAll;
                }

                //Build interesting attribute list
                List <string> attrs = new List <string>();
                attrs.AddRange(new string[] { "whenCreated", "name", "sAMAccountName", "cn" });
                if (retrieveGroupMembers)
                {
                    attrs.Add("member");
                }

                if (!string.IsNullOrEmpty(_config.GroupNameAttribute) && !attrs.Contains(_config.GroupNameAttribute))
                {
                    attrs.Add(_config.GroupNameAttribute);
                }

                LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0));
                cons.BatchSize = 0;

                LdapSearchResults results = conn.Search(_config.LdapSearchBase,
                                                        LdapConnection.SCOPE_SUB,
                                                        searchFilter,
                                                        attrs.ToArray(),
                                                        false,
                                                        cons);

                //Create outer groups collection if multiple groups are being looked up or none provided
                if (string.IsNullOrEmpty(optionalGroupName))
                {
                    resultXml = new XDoc("groups");
                }

                while (results.hasMore())
                {
                    LdapEntry nextEntry = null;
                    try {
                        nextEntry = results.next();
                    } catch (LdapException x) {
                        HandleLdapException(x);
                        continue;
                    }

                    //Create xml from search entry
                    if (resultXml == null)
                    {
                        resultXml = new XDoc("group");
                    }
                    else
                    {
                        resultXml.Start("group");
                    }

                    string name = string.Empty;

                    //If a groupnameattribute is configured, use that. Otherwise try the common ones.
                    if (!string.IsNullOrEmpty(_config.GroupNameAttribute))
                    {
                        name = GetAttributeSafe(nextEntry, _config.GroupNameAttribute);
                    }
                    else
                    {
                        name = GetAttributeSafe(nextEntry, "sAMAccountName"); //MS Active Directory
                        if (string.IsNullOrEmpty(name))
                        {
                            name = GetAttributeSafe(nextEntry, "uid"); //OpenLDAP
                        }
                        if (string.IsNullOrEmpty(name))
                        {
                            name = GetAttributeSafe(nextEntry, "name"); //OpenLDAP
                        }
                        if (string.IsNullOrEmpty(name))
                        {
                            name = GetAttributeSafe(nextEntry, "cn"); //Novell eDirectory
                        }
                    }

                    resultXml.Attr("name", name);
                    resultXml.Start("ldap-dn").Value(nextEntry.DN).End();
                    resultXml.Start("date.created").Value(ldapStringToDate(GetAttributeSafe(nextEntry, "whenCreated"))).End();

                    //Retrieve and write group membership to xml
                    LdapAttributeSet memberAttrSet = nextEntry.getAttributeSet();
                    LdapAttribute    memberAttr    = memberAttrSet.getAttribute("member");

                    // TODO MaxM: This currently does not differentiate between user and group
                    // members.

                    if (memberAttr != null)
                    {
                        foreach (string member in memberAttr.StringValueArray)
                        {
                            resultXml.Start("member");
                            resultXml.Attr("name", GetNameFromDn(member));
                            resultXml.Start("ldap-dn").Value(member).End();
                            resultXml.End();
                        }
                    }
                    if (string.IsNullOrEmpty(optionalGroupName))
                    {
                        resultXml.End();
                    }
                }
            } finally {
                UnBind(conn);
            }

            return(resultXml);
        }
Beispiel #18
0
        /// <summary>
        /// Retrieve information about one or more users
        /// </summary>
        /// <param name="retrieveGroupMembership">retrieving list of groups for each user will take longer</param>
        /// <param name="username">Username to lookup</param>
        /// <returns></returns>
        public XDoc GetUserInfo(bool retrieveGroupMembership, string username)
        {
            XDoc           resultXml = null;
            LdapConnection conn      = null;

            try {
                LdapSearchResults results = LookupLdapUser(retrieveGroupMembership, username, out conn);

                if (results.hasMore())
                {
                    LdapEntry nextEntry = null;
                    try {
                        nextEntry = results.next();
                    } catch (LdapException x) {
                        HandleLdapException(x);
                    }

                    if (nextEntry == null)
                    {
                        throw new ArgumentNullException("nextEntry");
                    }

                    //Create xml from search entry
                    resultXml = new XDoc("user");

                    string name = string.Empty;

                    //If a usernameattribute is configured, use that. Otherwise try the common ones.
                    if (!string.IsNullOrEmpty(_config.UserNameAttribute))
                    {
                        name = GetAttributeSafe(nextEntry, _config.UserNameAttribute);
                    }
                    else
                    {
                        name = GetAttributeSafe(nextEntry, "sAMAccountName"); //MS Active Directory
                        if (string.IsNullOrEmpty(name))
                        {
                            name = GetAttributeSafe(nextEntry, "uid"); //OpenLDAP
                        }
                        if (string.IsNullOrEmpty(name))
                        {
                            name = GetAttributeSafe(nextEntry, "name"); //OpenLDAP
                        }
                        if (string.IsNullOrEmpty(name))
                        {
                            name = GetAttributeSafe(nextEntry, "cn"); //Novell eDirectory
                        }
                    }

                    string displayName = BuildDisplayNameFromPattern(_config.DisplayNamePattern, nextEntry);

                    resultXml.Attr("name", name);
                    if (!string.IsNullOrEmpty(displayName))
                    {
                        resultXml.Attr("displayname", displayName);
                    }

                    resultXml.Start("ldap-dn").Value(nextEntry.DN).End();
                    resultXml.Start("date.created").Value(ldapStringToDate(GetAttributeSafe(nextEntry, "whenCreated"))).End();
                    resultXml.Start("firstname").Value(GetAttributeSafe(nextEntry, "givenname")).End();
                    resultXml.Start("lastname").Value(GetAttributeSafe(nextEntry, "sn")).End();
                    resultXml.Start("phonenumber").Value(GetAttributeSafe(nextEntry, "telephonenumber")).End();
                    resultXml.Start("email").Value(GetAttributeSafe(nextEntry, "mail")).End();
                    resultXml.Start("description").Value(GetAttributeSafe(nextEntry, "description")).End();

                    //Retrieve group memberships

                    if (string.IsNullOrEmpty(_config.GroupMembershipQuery))
                    {
                        LdapAttributeSet memberAttrSet = nextEntry.getAttributeSet();

                        LdapAttribute memberAttr = null;
                        if (memberAttrSet != null)
                        {
                            memberAttr = memberAttrSet.getAttribute(_config.GroupMembersAttribute);
                        }

                        if (memberAttr != null)
                        {
                            resultXml.Start("groups");
                            foreach (string member in memberAttr.StringValueArray)
                            {
                                resultXml.Start("group");
                                resultXml.Attr("name", GetNameFromDn(member));
                                resultXml.Start("ldap-dn").Value(member).End();
                                resultXml.End();
                            }
                            resultXml.End();
                        }
                    }
                    else
                    {
                        //Perform custom query to determine groups of a user
                        PopulateGroupsForUserWithQuery(resultXml, username, conn);
                    }
                }
            } finally {
                UnBind(conn);
            }

            return(resultXml);
        }
Beispiel #19
0
 public LdapOrganization(LdapAttributeSet attributeSet)
     : base(attributeSet)
 {
     OrganizationUnit = attributeSet.getAttribute("ou")?.StringValue;
 }
Beispiel #20
0
        private LdapIdentityUser CreateUserFromAttributes(string distinguishedName, LdapAttributeSet attributeSet)
        {
            var LdapIdentityUser = new LdapIdentityUser
            {
                ObjectSid         = attributeSet.getAttribute("objectSid")?.StringValue,
                ObjectGuid        = attributeSet.getAttribute("objectGUID")?.StringValue,
                ObjectCategory    = attributeSet.getAttribute("objectCategory")?.StringValue,
                ObjectClass       = attributeSet.getAttribute("objectClass")?.StringValue,
                IsDomainAdmin     = attributeSet.getAttribute("memberOf") != null && attributeSet.getAttribute("memberOf").StringValueArray.Contains("CN=Domain Admins," + this._ldapSettings.SearchBase),
                MemberOf          = attributeSet.getAttribute("memberOf")?.StringValueArray,
                CommonName        = attributeSet.getAttribute("cn")?.StringValue,
                UserName          = attributeSet.getAttribute("name")?.StringValue,
                SamAccountName    = attributeSet.getAttribute("sAMAccountName")?.StringValue,
                UserPrincipalName = attributeSet.getAttribute("userPrincipalName")?.StringValue,
                Name = attributeSet.getAttribute("name")?.StringValue,
                DistinguishedName = attributeSet.getAttribute("distinguishedName")?.StringValue ?? distinguishedName,
                DisplayName       = attributeSet.getAttribute("displayName")?.StringValue,
                FirstName         = attributeSet.getAttribute("givenName")?.StringValue,
                LastName          = attributeSet.getAttribute("sn")?.StringValue,
                Description       = attributeSet.getAttribute("description")?.StringValue,
                Phone             = attributeSet.getAttribute("telephoneNumber")?.StringValue,
                EmailAddress      = attributeSet.getAttribute("mail")?.StringValue,
                Address           = new LdapAddress
                {
                    Street      = attributeSet.getAttribute("streetAddress")?.StringValue,
                    City        = attributeSet.getAttribute("l")?.StringValue,
                    PostalCode  = attributeSet.getAttribute("postalCode")?.StringValue,
                    StateName   = attributeSet.getAttribute("st")?.StringValue,
                    CountryName = attributeSet.getAttribute("co")?.StringValue,
                    CountryCode = attributeSet.getAttribute("c")?.StringValue
                },

                SamAccountType = int.Parse(attributeSet.getAttribute("sAMAccountType")?.StringValue ?? "0"),
            };

            return(LdapIdentityUser);
        }