How to Authenticate to Active Directory Services (ADs) using .NET 3.5 / C#
Posted
by Ranger Pretzel
on Stack Overflow
See other posts from Stack Overflow
or by Ranger Pretzel
Published on 2010-03-26T19:30:10Z
Indexed on
2010/03/26
19:33 UTC
Read the original article
Hit count: 1202
After much struggling, I've figured out how to authenticate to my company's Active Directory using just 2 lines of code with the Domain, Username, and Password in .NET 2.0 (in C#):
// set domain, username, password, and security parameters
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain,
username, password, AuthenticationTypes.Secure | AuthenticationTypes.SecureSocketsLayer);
// force Bind to AD server to authenticate
object obj = entry.NativeObject;
If the 2nd line throws an exception, then the credentials and/or parameters were bad. (Specific reason can be found in the exception.) If no exception, then the credentials are good.
Trying to do this in .NET 3.5 looks like it should be easy, but has me at a roadblock instead. Specifically, I've been working with this example:
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain);
using (domainContext)
{
return domainContext.ValidateCredentials(UserName, Password);
}
Unfortunately, this doesn't work for me as I don't have both ContextOptions set to Sealed/Secure and SSL (like I did above in the .NET 2.0 code.)
There is an alternate constructor for PrincipalContext that allows setting the ContextOptions, but this also requires supplying a Distinguished Name (DN) of a Container Object and I don't know exactly what mine is or how I would find out.
public PrincipalContext(ContextType contextType, string name, string container, ContextOptions options);
// container:
// The container on the store to use as the root of the context. All queries
// are performed under this root, and all inserts are performed into this container.
// For System.DirectoryServices.AccountManagement.ContextType.Domain and System.DirectoryServices.AccountManagement.ContextType.ApplicationDirectory
// context types, this parameter is the distinguished name of a container object.
Any suggestions?
© Stack Overflow or respective owner