vml19
vml19

Reputation: 3864

Log in using AD credentials in C#

I am using following code to validate AD users

string strLDAP = "LDAP://dc=ADServerIP/cn=Users,DC=Domain;
DirectoryEntry entry = new DirectoryEntry(strLDAP, usr, pwd);
object nativeObject = entry.NativeObject;
return true;

I am getting the following exception when executing

object nativeObject = entry.NativeObject;

System.Runtime.InteropServices.COMException (0x80005000): Unknown error (0x80005000)
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_NativeObject()

The same code is working for another AD server. What may be the issue?

Upvotes: 0

Views: 3195

Answers (1)

marc_s
marc_s

Reputation: 754240

Are you working on .NET 3.5 or newer? If so, you can use the System.DirectoryServices.AccountManagement namespace and easily verify your credentials:

// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", usr, pwd))
{
    // validate the credentials
    bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}

It's simple, it's reliable, it's 100% C# managed code on your end - what more can you ask for? :-)

Read all about it here:

Upvotes: 7

Related Questions