[英]ASP.NET MVC 5 Forms Authentication using ActiveDirectoryMembershipProvider and IsAuthenticated
我正在将ASP.NET MVC 5与Forms auth和AD成员资格提供程序一起使用,如下所示:
<authentication mode="Forms">
<forms name=".ADAuthCookie" loginUrl="~/Account/Login" defaultUrl="~/" timeout="20" slidingExpiration="true" protection="All" />
</authentication>
<membership defaultProvider="ADMembershipProvider">
<providers>
<clear/>
<add name="ADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider"
connectionStringName="ADConnectionString"
attributeMapUsername="sAMAccountName"
enableSearchMethods="true" />
</providers>
</membership>
我启用了匿名身份验证,并禁用了 Windows身份验证。
我可以针对AD成功进行身份验证,并且User.Identity.Name
的值确实显示了我的用户名。 但是IsAuthenticated
是错误的。 为什么?
我想在布局中使用一些标志来显示/隐藏导航。 现在,在我看来,我正在求助于此:
@if (@User.Identity.Name == "") { show insecure content }
我正在使用自己在AccountController
定义的Login
方法,如下所示:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(Login model, string returnUrl = "")
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
_logger.Info("AccountController.Login() User.Identity.Name=" + User.Identity.Name);
FormsAuthentication.RedirectFromLoginPage(model.UserName, model.RememberMe);
}
ModelState.AddModelError("", "Incorrect username and/or password");
}
return View(model);
}
我也不完全相信/ Logout中的以下方法可以正常工作:
HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
FormsAuthentication.SignOut();
Session.Abandon();
也许我在使用ActiveDirectoryMembershipProvider
时并不完全了解User.Identity
的预期行为。
如果使用的是脚手架MVC5应用程序,则有一个用于SignInAsync
的部分,您必须在其中设置用于身份验证的声明身份。 我必须对我的做出一些更改,但它看起来像这样:
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
我遇到了同样的问题,并且跟随这篇文章以及其他一些文章来解决它: http : //kevin-junghans.blogspot.com/2013/12/using-claims-in-aspnet-identity.html
在上一篇文章中有人告诉我,MVC5取消了表单身份验证,而是主张声明,我可能错了,也许有人可以对此进行更多说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.