我需要在我的应用程序中使用MVC 5
实现表单和Windows身份验证的混合模式身份验证这意味着我需要在不使用ASP.NET成员资格提供程序的情况下实现Active Directory身份验证。
答案 0 :(得分:0)
好像您希望将Active Directory用户用作ASP.NET Identity用户.. 为UserLogin信息准备一个方法(用于添加到ASPNET Idenity)
private UserLoginInfo GetWindowsLoginInfo(string userId, string password)
{
string result = IsValidADUser(userId, password);
return result != "" ? new UserLoginInfo("Windows", result) : null;
}
并创建一个验证活动目录的方法
private string IsValidADUser(string userName, string password)
{
String adServerName = "LDAP://<<your LDAP String>>";
var sid = "";
try
{
var directoryEntry = new DirectoryEntry();
if (!string.IsNullOrEmpty(adServerName))
{
directoryEntry.Path = adServerName;
directoryEntry.Username = userName;
directoryEntry.Password = password;
directoryEntry.AuthenticationType = AuthenticationTypes.Secure;
}
else
{
throw new Exception("Invalid AD");
}
if (directoryEntry.NativeObject != null)
{
// Verify the user is locked or not
DirectorySearcher searcher = new DirectorySearcher(directoryEntry);
searcher.Filter = "(SAMAccountName=" + userName + ")";
searcher.CacheResults = false;
SearchResult result = searcher.FindOne();
if (result == null || result.Properties["lockoutTime"][0].ToString() != "0")
{
throw new Exception("User Account is locked");
}
else
{
var sidInBytes = (byte[])result.Properties["objectSid"][0];
sid = new SecurityIdentifier(sidInBytes, 0).ToString();
//isValidUser = true;
}
}
}
catch (Exception ex)
{
throw new Exception("AD:" + ex.Message);
}
return sid;
}