我有活动目录的用户名和密码,我想使用C#登录到活动目录。我如何在Windows窗体中执行此操作?
答案 0 :(得分:4)
连接到Active Directory非常简单。
您必须使用DirectoryEntry
对象(在命名空间System.DirectoryServices
中)。
此对象的构造函数在参数中包含三个字符串:
LDAP://your-name-AD
using System.DirectoryServices;
try
{
DirectoryEntry Ldap = new DirectoryEntry("LDAP://your-name-AD", "Login", "Password");
}
catch(Exception Ex)
{
Console.WriteLine(Ex.Message);
}
答案 1 :(得分:4)
这个问题来自几年前,我希望这个答案可以在将来帮助人们。 这对我有用:
添加以下参考:
之后,您可以在应用中使用此代码:
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOUR DOMAIN");
bool Valid = pc.ValidateCredentials("User", "password");
名为有效的变量,如果logIn为Ok,则会显示 True 值。
有关详细信息,请访问this page。该页面来自此处, stackOverFlow ,它将显示有关以下内容的大量信息:“使用MS Active Directory登录”
答案 2 :(得分:2)
你去吧。此方法针对Active Directory验证username/password
,并且在很长一段时间内一直是我的函数工具箱的一部分。
//NOTE: This can be made static with no modifications
public bool ActiveDirectoryAuthenticate(string username, string password)
{
bool result = false;
using (DirectoryEntry _entry = new DirectoryEntry())
{
_entry.Username = username;
_entry.Password = password;
DirectorySearcher _searcher = new DirectorySearcher(_entry);
_searcher.Filter = "(objectclass=user)";
try
{
SearchResult _sr = _searcher.FindOne();
string _name = _sr.Properties["displayname"][0].ToString();
result = true;
}
catch
{ /* Error handling omitted to keep code short: remember to handle exceptions !*/ }
}
return result; //true = user authenticated!
}
执行此操作的软件必须在域内的计算机上运行,显然(或者您没有Active Directory来验证您的凭据)。
答案 3 :(得分:0)
较短的答案是添加参考 System.DirectoryServices.AccountManagement
然后使用 UserPrincipal.Current.Context.ValidateCredentials(“username”,“password”);
但我想您需要加入要验证的域名。