Tuesday, June 18, 2013

Authenticating a user against a specific domain (C#)

In the example below I am authenticating an imaginary user called usernameHere that has a password of passwordHere against the mydomainHere.com domain. In this example, the user would normally login using something like this: mydomainHere\usernameHere and then enter the password. The .com was added to the domain because that is typically how domains are set up. However, if you have a different long name for the domain, you should use that.

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

...
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "mydomainHere.com"))
{
     // validate the credentials
     bool isValid = pc.ValidateCredentials("usernameHere", "passwordHere", ContextOptions.Negotiate);
     Console.WriteLine("Valid: " + isValid);
    
}


You will need to add a reference to System.DirectoryServices.dll and System.DirectoryServices.AccountManagement.dll in order for this to work. If you don't have version 3.5 or newer of .NET, you will not have these methods available to you. This link has many other methods that you can try.

As a side note, here is a article that shows lots of code snippets for doing common tasks in Active Directory using C#.

No comments: