Open the web.config file.
First of all, you will need a connectionString for your ActiveDirectory:
<connectionStrings> ... <add name="ADConnectionString" connectionString=LDAP://*adserver*/DC=*domain* /> ... </connectionStrings>
Scroll down to the <membership> . Make sure the defaultProvider attribute is set to <membership> , for example:
<membership defaultProvider="SimpleMembershipProvider">
Then add a new provider for AD members inside <providers> :
<add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" />
This should do the trick for web.config. Now we need to authorize AD users at login. Go to the AccountController Login action. First, we try to authenticate the user through ActiveDirectory; there is a convenient class called PrincipalContext in the System.DirectoryServices.AccountManagement namespace. If this fails, we use the default membership provider:
public ActionResult Login(LoginModel model, string returnUrl) { try { // try to auth user via AD using (PrincipalContext pc = new PrincipalContext(ContextType.Domain)) { if (pc.ValidateCredentials(model.UserName, model.Password)) { FormsAuthentication.SetAuthCookie(model.UserName, false); return RedirectToAction("Index", "Home"); } } // try the default membership auth if active directory fails if (Membership.ValidateUser(model.UserName, model.Password)) { FormsAuthentication.SetAuthCookie(model.UserName, false); if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "Login failed"); } } catch { } GetErrorsFromModelState(); return View(model); }
For later requirements, you can get the current ActiveDirectory username with the UserPrincipal class:
using (var context = new PrincipalContext( ContextType.Domain)) { using (var aduser = UserPrincipal.FindByIdentity( context,IdentityType.SamAccountName, HttpContext.User.Identity.Name)) { ... } }
Hope this helps and I havenβt missed anything.