Authenticate against ActiveDirectory
-
29-04-2021 - |
Question
I did a little Googling and I came accross this promising code
System.DirectoryServices.AccountManagement.PrincipalContext pc = new System.DirectoryServices.AccountManagement.PrincipalContext(ContextType.Domain, "YOURDOMAIN")
// validate the credentials
bool validatedOnDomain = pc.ValidateCredentials(userName, tb.Text.ToString());
userName is initialized as the Windows login name. It's also a string tb.Text.ToString() is the textbox that is being used for typing the password
Updated code and it's working. Thanks all
MSDN says that PrincipalContext can use two arguments
Solution
Try to figure out this code.. This is working perfectly in my project.
public bool ValidateUser(string varDomain, string varUserName, string varPwd)
{
Boolean isValidUser;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, varDomain))
{
isValidUser = pc.ValidateCredentials(varUserName, varPwd);
}
return isValidUser;
}
OTHER TIPS
type used in a using statement must be implicitly convertible to 'System.IDisposable'
Means that you need to change your code to:
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
// validate the credentials
bool validatedOnDomain = pc.ValidateCredentials(userName, tb.Text.ToString());
Basically it's just telling you that you cannot use a PrincipalContext
in a using
statement, because PrincipalContext
does not implement the interface called IDisposable
.
EDIT
As marc_s
has pointed out below, the PrincipalContext
you are using is not the right one. It seems to live in your own namespace. You should be using that from System.DirectoryServices.AccountManagement
.