I'm using ASP.NET MVC 5 with Forms auth and AD membership provider as follows:
<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>
I have Anonymous Auth Enabled , and Windows Auth Disabled .
I can successfully authenticate against AD, and the value of User.Identity.Name
indeed shows my username. However IsAuthenticated
is false. Why?
I'd like to use some flag in my layout to show/hide navigation. Right now, I'm resorting to this in my view:
@if (@User.Identity.Name == "") { show insecure content }
I am using my own Login
method as defined in my AccountController
as follows:
[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);
}
I'm also not entirely convinced that the following methods are working as expected in my /Logout:
HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
FormsAuthentication.SignOut();
Session.Abandon();
Perhaps I'm not entirely understanding the expected behavior of User.Identity
when using ActiveDirectoryMembershipProvider
.
If you are using the scaffolded MVC5 application there is a section for SignInAsync
where you must set the claims identity for authentication. I had to make some changes to mine but it will look like this:
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);
}
I had run into the same issue and followed this post along with some others to resolve it: http://kevin-junghans.blogspot.com/2013/12/using-claims-in-aspnet-identity.html
I was told in a previous post that MVC5 did away with form auth in favor of claims, I may be wrong and perhaps some one can shed more light on that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.