MVC 5中的Windows身份验证
本文关键字:身份验证 Windows 中的 MVC | 更新日期: 2023-09-27 18:13:23
我负责为我正在做的一个项目实现Windows身份验证。我找遍了所有的例子,但似乎没有一个适合我的情况。
所有拥有有效Windows帐户的用户都应该能够访问应用程序,但只有一些配置为Admin的用户应该能够访问站点的某些部分。
我认为应该使用:
User.Identity.IsAuthenticated
,但这总是返回false。我对此非常有限的理解意味着我认为这应该是正确的。如何使用用户登录的帐户自动对其进行身份验证,这样他们就不必输入用户名/密码组合了?
我正在使用MVC 5
您希望实现LDAP,并让它与您的活动目录接口
查看这个链接来开始你的工作:
http://www.schiffhauer.com/mvc-5-and-active-directory-authentication/下面是来自链接的源代码:
账户控制器:
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");
}
}
Account View Models:
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; }
}
最后网络。配置更新:
<?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>
这应该有助于你开始,一定要查看链接以获得更多的上下文思考。如果你需要更多的帮助,请告诉我