简体   繁体   中英

How do I authenticate user in ASP.NET Identity framework?

I am using a default ASP.NET 4.5 framework's ASP.NET MVC 5 project template. It has identity authentication framework configured with it.

I want to use Window's Active Directory with my project, so I followed this article - http://www.schiffhauer.com/mvc-5-and-active-directory-authentication/

And in my AccountController's login method I have

if (Membership.ValidateUser(model.Email, model.Password))
{
    CustomFormsAuthentication.SetAuthenticationCookie(model.Email, model,  model.RememberMe);
    return RedirectToAction("Index", "Home");
}

Where CustomFormsAuthentication class has

public static class CustomFormsAuthentication
{
    public static void SetAuthenticationCookie(string username, object obj, bool isPersistent)
    {
        const int version = 1;
        var json = new JavaScriptSerializer().Serialize(obj);
        var cookieStoreTime = isPersistent ? DateTime.Now.AddDays(7): DateTime.Now.AddDays(1);
        var ticket = new FormsAuthenticationTicket(version, username, DateTime.Now, cookieStoreTime, isPersistent, json);

        HttpContext.Current.Response.Cookies.Set(new HttpCookie(FormsAuthentication.FormsCookieName,
            FormsAuthentication.Encrypt(ticket)) {Expires = cookieStoreTime});
    }
}

But the user is never authenticated. The User.Identity.IsAuthenticated still shows false.

How do I go about this ?

Identity is incompatible with forms authentication (utilized by ASP.NET Membership here in your code). Even then, forms authentication is incompatible with Windows auth, which also is incompatible with Identity. If you want to authenticate using Windows credentials, then you need to change your Web.config to have:

...
 <system.web>
  ...
  <authentication mode="Windows"/>
  ...
 </system.web>
 ...

And then you can pretty much just remove all the Identity stuff as it won't work any more.

EDIT

The most important point here after the discussion in the comments is that multiple forms of authentication simultaneously is not a supported scenario in ASP.NET. You can technically do workarounds such that you basically proxy authentication to an LDAP server to verify AD credentials and then create/get an Identity/Membership user based on that to actually be the authenticated user.

However, here, I don't see any real attempt to do that, and even then, you're using ASP.NET Membership and forms auth to handle it, which precludes the use of Identity. Identity and forms auth are completely incompatible with each other.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM