根据Active Directory验证用户名和密码?
我如何根据Active Directory验证用户名和密码? 我只是想检查用户名和密码是否正确。
如果您使用.NET 3.5或更高版本,则可以使用System.DirectoryServices.AccountManagement
命名空间并轻松验证您的凭据:
// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
// validate the credentials
bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}
这很简单,它很可靠,它是您的最终的100%C#托管代码 - 您还能要求什么? :-)
在这里阅读所有内容:
更新:
正如这个其他SO问题(及其答案)中所述,对于用户的旧密码,此调用可能会返回True
的问题。 请注意这种行为,如果发生这种情况,请不要感到惊讶:-)(感谢@MikeGledhill指出这一点!)
我们在我们的Intranet上执行此操作
您必须使用System.DirectoryServices;
这里是代码的胆量
using (DirectoryEntry adsEntry = new DirectoryEntry(path, strAccountId, strPassword))
{
using (DirectorySearcher adsSearcher = new DirectorySearcher(adsEntry))
{
//adsSearcher.Filter = "(&(objectClass=user)(objectCategory=person))";
adsSearcher.Filter = "(sAMAccountName=" + strAccountId + ")";
try
{
SearchResult adsSearchResult = adsSearcher.FindOne();
bSucceeded = true;
strAuthenticatedBy = "Active Directory";
strError = "User has been authenticated by Active Directory.";
}
catch (Exception ex)
{
// Failed to authenticate. Most likely it is caused by unknown user
// id or bad strPassword.
strError = ex.Message;
}
finally
{
adsEntry.Close();
}
}
}
这里介绍的几种解决方案缺乏区分错误的用户/密码和需要更改的密码的能力。 这可以通过以下方式完成:
using System;
using System.DirectoryServices.Protocols;
using System.Net;
namespace ProtocolTest
{
class Program
{
static void Main(string[] args)
{
try
{
LdapConnection connection = new LdapConnection("ldap.fabrikam.com");
NetworkCredential credential = new NetworkCredential("user", "password");
connection.Credential = credential;
connection.Bind();
Console.WriteLine("logged in");
}
catch (LdapException lexc)
{
String error = lexc.ServerErrorMessage;
Console.WriteLine(lexc);
}
catch (Exception exc)
{
Console.WriteLine(exc);
}
}
}
}
如果用户密码错误,或者用户不存在,则会包含错误
“8009030C:LdapErr:DSID-0C0904DC,注释:AcceptSecurityContext错误,数据52e,v1db1”,
如果用户密码需要更改,它将包含
“8009030C:LdapErr:DSID-0C0904DC,注释:AcceptSecurityContext错误,数据773,v1db1”
lexc.ServerErrorMessage
数据值是Win32错误代码的十六进制表示。 这些错误代码会以其他方式调用Win32 LogonUser API调用返回。 下面的列表总结了一系列具有十六进制和十进制值的常见值:
525 user not found (1317)
52e invalid credentials (1326)
530 not permitted to logon at this time (1328)
531 not permitted to logon at this workstation (1329)
532 password expired (1330)
533 account disabled (1331)
701 account expired (1793)
773 user must reset password (1907)
775 user account locked (1909)
链接地址: http://www.djcxy.com/p/6123.html
上一篇: Validate a username and password against Active Directory?