您可以通过直接根据用户的域凭据对用户进行身份验证来保护 Active Directory 网络上的 MVC Web 应用程序。
第 1 步:ACCOUNTCONTROLLER.CS
将您的 AccountController.cs 文件替换为以下内容:
using System.Web.Mvc;
using System.Web.Security;
using MvcApplication.Models;
public class AccountController : Controller
{
public ActionResult Login()
{
return this.View();
}
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (!this.ModelState.IsValid)
{
return this.View(model);
}
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (this.Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return this.Redirect(returnUrl);
}
return this.RedirectToAction("Index", "Home");
}
this.ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");
return this.View(model);
}
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return this.RedirectToAction("Index", "Home");
}
}
第 2 步:ACCOUNTVIEWMODELS.CS
更新您的 AccountViewModels.cs(或任何您的 Account 模型类的名称)以仅包含此 LoginModel 类:
using System.ComponentModel.DataAnnotations;
public class LoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
第 3 步:WEB.CONFIG
最后,更新您的 Web.config 文件以包含这些元素。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authentication mode="Forms">
<forms name=".ADAuthCookie" loginUrl="~/Account/Login" timeout="45" slidingExpiration="false" protection="All" />
</authentication>
<membership defaultProvider="ADMembershipProvider">
<providers>
<clear />
<add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" />
</providers>
</membership>
</system.web>
<connectionStrings>
<add name="ADConnectionString" connectionString="LDAP://primary.mydomain.local:389/DC=MyDomain,DC=Local" />
</connectionStrings>
</configuration>
获取 LDAP 连接字符串可能需要几个步骤:
安装适用于 Windows 7 的远程服务器管理工具。确保按照安装后说明通过控制面板将该功能添加到 Windows。
-
打开命令提示符并输入>dsquery server
假设命令返回以下内容:
CN=PRIMARY,CN=Servers,CN=DefaultFirstName,CN=Sites,CN=Configuration,DC=MyDomain,DC=Local
服务器名称由第一个 CN 值和最后两个 DC 值组成,以点分隔。所以是primary.mydomain.local。
端口是389。
端口和正斜杠之后的连接字符串部分是结果中以第一个"DC" 开头的部分。所以是DC=MyDomain,DC=Local。
-
所以完整的连接字符串是
LDAP://primary.mydomain.local:389/DC=MyDomain,DC=Local.
用户将只使用他们的用户名登录,而不使用域。所以正确的用户名是 Chris,而不是 MYDOMAIN\Chris。