[英]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.