因为您使用的是 AD LDS,所以我认为身份验证模式“Windows”不会有太大帮助。我相信您需要创建一个登录视图(此处为 /Account/Logon)并使用身份验证模式“表单”。
在 web.config 中输入以下内容
<authentication mode="Forms">
<forms name=".ADAuthCookie" loginUrl="~/Account/Logon" timeout="30" slidingExpiration="false" protection="All"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
可以使用 System.DirectoryServices.AccountManagement 对用户进行身份验证。控制器代码应如下所示:
public ActionResult Logon(LogonModel model)
{
if (model.Username != null && model.Password != null)
{
string container = "CN=...,DC=....,DC=...."; //Your container in LDS
string ldapserver = "server:port"; //LDS server
PrincipalContext context = new PrincipalContext(
ContextType.ApplicationDirectory,
ldapserver,
container,
ContextOptions.SimpleBind);
bool authenticate = context.ValidateCredentials(string.Format("CN={0},{1}", model.Username, container), model.Password, ContextOptions.SimpleBind);
if (authenticate)
{
FormsAuthentication.RedirectFromLoginPage(model.Username, false);
}
else
{
System.Threading.Thread.Sleep(5000);
this.ModelState.AddModelError("Password", "Wrong username or password");
}
}
return View("Logon", new LogonModel { Username = model.Username });
}
请注意,这只解决了身份验证问题,而不是授权问题。
您也可以使用会员提供商,但如果您正在寻找一个简单的解决方案,我认为这应该可以解决问题。