Quantcast
Channel: Active Directory and LDAP
Viewing all 191 articles
Browse latest View live

Trying to get information from Active Directory but not all returning

$
0
0

Hello,

This is my first attempt at accessing the Active Directory.   I enter database records from users in the active directory.

Recently it was brought to my attention that I am missing some names.

For instance, two guys in our department. One has his name in the list, but the other does not.   I had our IT guy look at the AD profiles and they are both in there and appear to be the same.

So I thought perhaps the filters are playing apart.  After testing different filters I can see the missing people.....but it only returns a set number of records. It does not return the full alphabet of active directory users (like one filter  always stops at the 'H's or 'G's).

Below are some commented out filters that I have tried.  The original filter brings back 614 records and it goes through the alphabet of names, but I am missing records.

Another filter will bring back only 312 or 313 records of which both missing and non-missing records are there but only up to the letter 'H' in the alpha bet.

Do I need to set a number of records allowed returned or something?  Or what filter will return ALL entries?  And how come when I don't use a filter at all I get back 156 records?

 '  search.Filter = "(&(objectClass=user)(objectCategory=person)(showInAddressBook=*))" '---This is used if not using the if statement below checking if it's person
        '  search.Filter = "(|(objectClass=user)(showInAddressBook=*))"    '  records - but missing records
        '  search.Filter = "(&(objectClass=user)(showInAddressBook=*))"    ' 614 records - but missing records
        '  search.Filter = "(objectClass=*)"                               ' 156 with missing records
        '  search.Filter = "(&(objectClass=*)(showInAddressBook=*))"       ' 585 missing records
        '  search.Filter = "(&(objectClass=user)(objectClass=*))"          ' 312 with missing records
        '  search.Filter = "(&(objectClass=person)(objectClass=user))"     ' 312 with missing records
        '  search.Filter = "(|(objectClass=person)(objectClass=user))"     ' 166 with missing records
        '  search.Filter = "(|(objectClass=*)(showInAddressBook=*))"       ' 156  records - but missing records
        ' NO filter at all and only 156 records ?

        search.Filter = "(objectClass=user)"    ' only 313 records returned and stops at letter H but missing records are included


        search.Sort.Direction = SortDirection.Ascending
        search.Sort.PropertyName = "DisplayName"
        search.PropertiesToLoad.Add("mail")
        search.PropertiesToLoad.Add("DisplayName")
        search.PropertiesToLoad.Add("physicalDeliveryOfficeName")
        search.PropertiesToLoad.Add("department")
        search.PropertiesToLoad.Add("telephoneNumber")
        search.PropertiesToLoad.Add("DistinguishedName")
        search.PropertiesToLoad.Add("objectClass")

Thanks for your time.


using a Read-Only domain controller with validate user method

$
0
0

We use an IIS 8 web farm, located in a separate AD site along with a read only domain controller.   When specifying the read only domain controller in the ActiveDirectoryMembershipProvider connection string, the getuser method works but the validateuser method fails with

"Event code: 4006  Event message: Membership credential verification failed."

 Is this a limitation of the RODC?  I would assume the validateuser method does not need to write/modify AD user attributes but I could be wrong.

Webform to update employee data in Active Directory

$
0
0

Hello!

I want to create a simple webform that our employees can use to update their office location and other attributes in Active Directory. I'd like users to be able to login, choose from a list of predefined data and submit that to either a database, CSV, or directly in Active Directory. Does anyone here have experience with creating anything like this?

Thanks, Jay! 

How to authenticate LDAP user with GSS Negotiate binding authentication using C#?

$
0
0

I am new to LDAP. I have written the below code that authenticates users with LDAP. I currently have to validate users with a server that has a biding authentication type of GSS-Negotiate. I couldn't find any examples to validate the user with such a binding authentication type. The below code I tried doesn't work on this binding authentication. What am I missing in the below code segment. Any help would be much appreciated. Also is there an internet LDAP server in which I can validate a user with GSS-Negotiate binding to test it out?

public static string AuthFunction_One(string identity, string password, string containerString, string adServerName, bool useLDAPS, IdentityType identityType)
    {

        string failedString = "FAILED";
        string successString = "SUCCESS";
        string returnValue = failedString;

        try
        {
            PrincipalContext ctx = null;
            if (useLDAPS)
            {
                ctx = new PrincipalContext(ContextType.Domain, adServerName, containerString, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);
            }
            else
            {
                ctx = new PrincipalContext(ContextType.Domain, adServerName, containerString);
            }
            UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(ctx, identityType, identity);
            PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();
            try
            {
                foreach (Principal result in oPrincipalSearchResult)
                {

                }

            }
            catch (Exception ex)
            {
                NLogHelper.GetInstance().Log("ADUtilityClass", "AuthFunction_One", NLog.LogLevel.Debug, "Failed to probe groups. Ex: " + ex.ToString());
            }

            if (ctx.ValidateCredentials(identity, password))
            {
                return successString;
            }
            else
            {
                return failedString;
            }
        }
        catch (Exception ex)
        {
            NLogHelper.GetInstance().Log("ADUtilityClass", "AuthFunction_One", NLog.LogLevel.Debug, "Error in function. Ex: " + ex.ToString());
            return failedString;
        }
    }

 

Get all users from active directory and save data in excel

$
0
0

Hi,

I am trying to get all users in Active directory and move the resultant data to Excel.

I have tried the below code:

    using (DirectoryEntry entry = new DirectoryEntry(LDAP, LDAPusername, LDAPPassword))
            {
                entry.RefreshCache();

                using (DirectorySearcher mySearcher = new DirectorySearcher(entry))
                {

                    mySearcher.Filter = "(&(objectCategory=Person))";
                    mySearcher.PropertiesToLoad.Add("sAMAccountName");
                    mySearcher.PropertiesToLoad.Add("displayName");
                    mySearcher.PropertiesToLoad.Add("mail"); //email

                    var resultCollection = mySearcher.FindAll();

string[] fldUserId = new string[4];
using (SearchResultCollection searchResultCollection = mySearcher.FindAll())
{
foreach (SearchResult searchResult in searchResultCollection)
{
fldUserId[0] = searchResult.Properties["sAMAccountName"][0].ToString();
 }
 }
 }
}

 I am trying to find user email, user Id (domain\Lan ID) and then save the data in excel.

Is the above code correct and efficient to get all user details ? How to pass the data to excel ?

Thanks

PrincipalContext error

$
0
0

 

using (var context = new PrincipalContext(ContextType.Machine, "ip_address_of_domain_controller", null, ContextOptions.Negotiate, "domain_name\\administrator", "password"))
     

Results in:

System.DirectoryServices.AccountManagement.PrincipalOperationException:

'Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again.

Connecting with ContextType.Domain work fine, but I need to connect to the domain controller to get the last successful logons. When I use a domain user (even if they are in the domain admins group) I get an Access is denied error with the above code.

Cheers

Danny

Fetching Active directory data - DirectoryEntry - Taking too long

$
0
0

Hi,

I am trying to list all users in a particular domain ( around 25,000 accounts ) and exporting the data to excel. I have used the below code which works, but is causing memory issues. Also, I want to list out if the user is active or inactive.

Below is the code :

using (DirectoryEntry entry = new DirectoryEntry(LDAP, LDAPusername, LDAPPassword))
            {
                entry.RefreshCache();

string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Drive:\foldername\MyID.xls;Extended Properties=""Excel 8.0;HDR=YES;""";

using (DirectorySearcher mySearcher = new DirectorySearcher(entry))
 {
 using (OleDbConnection conn = new OleDbConnection(connectionString))
 {
  using (OleDbCommand command = conn.CreateCommand())
 {
  conn.Open();
   mySearcher.Filter = "(&(objectCategory=person)(objectClass=user))";
   mySearcher.PropertiesToLoad.Add("sAMAccountName");
   mySearcher.PropertiesToLoad.Add("displayName");
   mySearcher.PropertiesToLoad.Add("mail");

   using (SearchResultCollection searchResultCollection = mySearcher.FindAll())
 {
foreach (SearchResult searchResult in searchResultCollection)
  {
  if (searchResult.Properties.Contains("sAMAccountName"))
   {
    fldUserId = searchResult.Properties["sAMAccountName"][0].ToString();
    }

   if (searchResult.Properties.Contains("mail"))
   {
   fldUserEmail = searchResult.Properties["mail"][0].ToString();
    }
  command.Parameters.Add("@Email", SqlDbType.VarChar).Value = fldUserEmail;
  command.CommandText = @"INSERT INTO [sheet1$] (UsersID, Email, Status) VALUES('" + fldUserId + "',@Email)";

command.ExecuteNonQuery();
  }
}
}
}
}
}

How to add the active/inactive status ?  How to improve the performance of the code?

Thanks

Type or namespace 'AccountManagement' does not exist in the namespace 'System.DirectoryServices'

$
0
0

I have the following namespace defined in my asp.net c# (VS 2010) app but still get the above error. What am I doing wrong?

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;


 


Struggling to save document in a virtual folder on the server

$
0
0

I am not able to save file to a virtual folder using the code below. Any idea?

The error I get is:   Exception Details: System.IO.DirectoryNotFoundException

            string sVirtualFolder = @"\\mydomain.cs\Apps\Product\Library\MyFiles";
            string fileName = FileUpload1.FileName;

            FileUpload1.SaveAs(Server.MapPath(sVirtualFolder) + "\\" + fileName);
            Response.Redirect(Request.Url.AbsoluteUri);



Basic Auth is not working in IE

$
0
0

Hi,

I am using below code to login another website with credentials. Unfortunately this is working in Chrome and not in IE. Please let me know how this will work in IE

window.open("https://UserName:Password@WebURL.COM");

Trouble Getting AD User Information

$
0
0

The following code returns the logged on user name if site is run on local IIS but if won't return the name if running on the server.

What do I need to do to fix it?

        DirectoryEntry GetDirectoryEntry(string name)
        {
            string[] arr = new string[] { "sAMAccountName", "givenName", "sn", "mail" };
            DirectoryEntry entry = new DirectoryEntry("LDAP://" + this.AD + "/dc=mydomain,dc=zz");
            DirectorySearcher searcher1 = new DirectorySearcher(entry);
            searcher1.Filter = "(&(objectClass=user)(sAMAccountName=" + name + "))";
            try
            {
                SearchResult r = searcher1.FindOne();
                DirectoryEntry de = r.GetDirectoryEntry();
                return de;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

Delay when calling DirectoryEntry's RefreshCache

$
0
0

We are finding a significant delay (11 or more seconds depending on environment and load) when calling .NET's System.DirectoryServices.DirectoryEntry.RefreshCache(). Details are provided in sections below. Does anyone have ideas as to what processes could be causing the delay? Typical causes? Methods to prove/disprove theories?

Timing: The delay described above occurs between the time that RefreshCache() is called and the first Syn...Ack...ClientHello packets are sent to the DC.

Frequency: If test iterations are spaced well enough apart, this problem occurs at the beginning of each test iteration. Under more intense test loads, the problem may skip a test iteration or two. 

Subsequent connection attempts within each test iteration typically perform well (I don't know why multiple connections are made per iteration - an issue for another day). 

Tech: The client computer that hosts the code is a member of a different domain than the Active Directory server. Trusts have been established between domains.

Code:

AuthenticationTypes authTypes = AuthenticationTypes.SecureSocketsLayer;
String connect = "LDAP://servername.otherdomain:636/DC=otherdomain"
DirectoryEntry de = new DirectoryEntry(connect, serviceAccount, PWD, authTypes)
de.RefreshCache(); // The delay is specific to this line.

// And so on...
dtree = de.Children;
policy = new DomainPolicy(de);
...

Thanks

iOS HTML5 File Upload with Asp.Net Windows Authentication

$
0
0

 I'm trying to upload files to a Asp.Net application (SharePoint) that has Windows Authentication enabled. The upload works fine with Android, desktop, but iOS is giving me trouble.

I did some research and came across this question: iOS 6 (iPhone/iPad) Image Upload "Request Body Stream Exhausted" with NTLM/Windows Authentication It seems this is a bug in Safari for iOS. The answer in this post does not help me.

I must use windows authentication, and I am not allowed to create another web app.

Is there any sort of hack, or workaround to this? The only one I can think of is create a separate app to handle uploads, but like I said, I am not allowed to do that.

Query AD using LDAP with Multiple sAMAccountNames?

$
0
0

I'm trying to figure out how to query AD using LDAP but passing multiple sAMAccountNames. My LDAP query works fine if I am passing one but I guess I am trying to figure out how to pass these as an array to grab their email addresses from AD. I should be able to work the C# code part out, I just need help with the LDAP query. Thanks all!

add users to posixgroup in openldap return protocal error

$
0
0

Hi all, I am trying to connect to openldap server (v3) using LdapDirectoryIdentifier  and establish LdapConnection connection ok with admin user and I have created new organizationalUnit  call Groups and then added new posixGroup s call  portal , testbed and gave different gidnumbers 

then i have created a  user  (PosixAccount) and set default gidNumber as portal gid number ... successfully created all above. but now I need to add user to above groups

so I have call below call as Modifyrequest to group dn to add user as memberid

                myLdapConnection.Bind();
                string groupdn = "cn=portal,ou=Groups" + dc;
                string userdn = "cn=test2,ou=Customers + dc;
                //String[] attribVals = new String[1];
                //attribVals[0] = userdn;
                ModifyRequest modifyreq = new ModifyRequest(groupdn, DirectoryAttributeOperation.Replace, "memberUid", userdn);

                // create the PermissiveModify control to better control modification behavior.
                PermissiveModifyControl permissiveModify = new PermissiveModifyControl();

                modifyreq.Controls.Add(permissiveModify);
                ModifyResponse response = (ModifyResponse)myLdapConnection.SendRequest(modifyreq);

I get below error
error occurred - System.DirectoryServices.Protocols.DirectoryOperationException: A protocol error occurred. at System.DirectoryServices.Protocols.LdapConnection.ConstructResponse(Int32 messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, Boolean exceptionOnTimeOut) at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request, TimeSpan requestTimeout) at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request) 

anyone know how to solve this please... I have tried to create a group of type groupOfNames as well there I can see a attribute call member I have tried to add users to this attribute that also failed. 

Any help would be great 


Add EF Model for Profile Data when using Azure AD for User Authentication

$
0
0

Hi All,

I'm pretty new to ASP.NET and AD and I'm looking for information on how I would add an Entity Framework Model for User Profile Data when using Azure AD for User Authentication.

I've got my Azure AD up and running and have created a new .NET 4.5.2 MVC site in VS2015 and linked it to the AD. This all works fine and I'm able to login using a user setup on my AD.

This is where it gets a bit confusing for me. The code that VS generates is totally different to what is shown in the tutorials/videos on this site and none of them seem to cover what I want to do. Which seems a bit strange to me, but maybe I'm not thinking along best practices.

If I create an MVC site with authentication set to 'Individual User Accounts' it creates the Identity Model with an ApplicationUser class which I can add additional properties to.

Can anyone point me to any resources or at least in the right direction.

Thanks,

Richard

openldap group user management fails - memeberof attribute undefined

$
0
0

Hi all, I am strugling to add users to a group i have created in my openldap server. users listed under ou=users,dc=....  and i have created ou call  groups and sub group under groups call testusers then i have created new user cal test11 and trying to add to group testusers.. I tried both way add memberuid in group attribute   failed. then i tried add memberOf attribute in user to say user is memberof testusers....

then i tried member attribute bcos I have seen it some where in a forum. but that fails too.. anyone to help me on how to add members to groups?

I am querying the Active Directory. What should I do to enale my website application accessing the Active Directory?

$
0
0

I am querying the Active Directory for information about the user email and other properties. I know how to perform this. However, my website should have permission to access the server that host the active directory. Should I make it by the Application pool identity or using another technique?

Problems getting new DirectoryEntry prior to search of AD

$
0
0

Here is a sanitized version of the code I am trying to get working

The call in Main is to 

DirectoryEntry myLdapConnection = createDirectoryEntry();

static DirectoryEntry createDirectoryEntry()
{
// create and return new LDAP connection with desired settings

String myADSPath = "LDAPS://server.bozo.clown.com:636/OU=365Users,DC=bozo,DC=clown,DC=com";
DirectoryEntry ldapConnection = new DirectoryEntry(myADSPath, @"adminuser@bozo.clown.com", @"whatever12_Password", AuthenticationTypes.Secure);
return ldapConnection;
}

When I try to make the call for DirectoryEntry de =new DirectoryEntry(adsPath,username,
password,AuthenticationTypes.Secure) it returns a DirectoryEntry object, ldapConnection,
but many of the attributes in debugger for the value, ldapConnection, returned, show this type of thing:


'ldapConnection.AdsObject' threw an exception of type
'System.Runtime.InteropServices.COMException'
'ldapConnection.ContainerObject' threw an exception of
'System.Runtime.InteropServices.COMException'
type'ldapConnection.Guid' threw an exception of type
'System.Runtime.InteropServices.COMException'
'ldapConnection.IsContainer' threw an exception of type
'System.Runtime.InteropServices.COMException'

Same for Name, NativeObject, NativeGuid,Object Security....

Examining this object using VS2010....

Do anyone have any relevant references or advice on this problem and how to resolve it? (code snippets most welcome)

Unknown username or bad password encountered in web application

$
0
0

My web application is using asp.net c#. The login page connects to active directory. The parent and child domain controller. The problem only encountered by users acessing the child domain controller. An error displayed is "unknown username or bad
password"

The unexplained part is sometimes the login page is working okay. Sometimes its not.

I hope someone can help me on this or at least give me an idea why this happening.
Viewing all 191 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>