61

What are the high level steps to authenticate users of an ASP.NET MVC application against Active Directory?

I presume something like:

  1. Modify web.config to use Windows authentication
  2. Configure web.config to use the ActiveDirectoryMembershipProvider
  3. Configure the web.config to use a custom RoleProvider that looks in AD

Does the above look sensible, and if so, where do I put the valid user detection logic?

In my case a valid user is someone on a specific AD domain.

0

3 Answers 3

89

Forms Authentication

You can use the normal forms authentication to authenticate a user against an Active Directory, for that you just need you AD connection string:

<connectionStrings>
  <add name="ADConn" connectionString="LDAP://YourConnection" />
</connectionStrings>

and add the Membership Provider to use this connection:

<membership defaultProvider="ADMembership">
  <providers>
    <add name="ADMembership"
         type="System.Web.Security.ActiveDirectoryMembershipProvider,
               System.Web,
               Version=2.0.0.0, 
               Culture=neutral,
               PublicToken=b03f5f7f11d50a3a"
         connectionStringName="ADConn"
         connectionUsername="domain/user"
         connectionPassword="pwd" />
  </providers>
</membership>

you will need to use username@domain to successfully authenticate the user.

Here is something to get you started


Windows Authentication

If you start your project new, you can always select Intranet application from the template and all is taken care for you

enter image description here

If you want to do it manually, you need to change:

  1. Enable Windows Authentication
  2. Disable Anonymous authentication

for detailed info on doing this on IIS7/8 and IISExpress:

IIS 7 & IIS 8

  1. Open IIS Manager and navigate to your website.
  2. In Features View, double-click Authentication.
  3. On the Authentication page, select Windows authentication. If Windows authentication is not an option, you'll need to make sure Windows authentication is installed on the server.

    To enable Windows authentication on Windows: a) In Control Panel open "Programs and Features". b) Select "Turn Windows features on or off". c) Navigate to Internet Information Services > World Wide Web Services > Security and make sure the Windows authentication node is checked.

    To enable Windows authentication on Windows Server: a) In Server Manager, select Web Server (IIS) and click Add Role Services b) Navigate to Web Server > Security and make sure the Windows authentication node is checked.

  4. In the Actions pane, click Enable to use Windows authentication.

  5. On the Authentication page, select Anonymous authentication.
  6. In the Actions pane, click Disable to disable anonymous authentication.

IIS Express

  1. Right click on the project in Visual Studio and select Use IIS Express.
  2. Click on your project in the Solution Explorer to select the project.
  3. If the Properties pane is not open, open it (F4).
  4. In the Properties pane for your project: a) Set "Anonymous Authentication" to "Disabled". b) Set "Windows Authentication" to "Enabled".

In your web.config have something like

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

  <authorization>
    <deny users="?" />
  </authorization>
</system.web>

and that's it!

Now, when you want the user identity, just call

@User.Identity.Name

and this will show you the Domain\Username like for me :

enter image description here

Here is something to get you started

7
  • 2
    I don't get it, no login page? It should either ask to login or get the currently logged in user no? Not sure I understand since you hard coded the username/pwd in the web.config Mar 18, 2016 at 19:35
  • @coolbreeze there is nothing hardcoded, the username comes from when you login in the Windows computer, that's what Windows authentication is, so why would it ask for a password again?
    – balexandre
    Mar 18, 2016 at 20:21
  • I'm referring to this ``` connectionStringName="ADConn" connectionUsername="domain/user" connectionPassword="pwd" />``` Mar 18, 2016 at 20:24
  • you don't need anything, that's a simple example for the MembershipProvider, the connection string is a LDAP string: connectionString="LDAP://YourConnection"
    – balexandre
    Mar 18, 2016 at 21:24
  • @coolbreeze - just in case it wasn't clear (sorry if I'm piling on) - think of Active Directory as a database and LDAP is the "technology" that helps communicate with the database. The connection string in web.config only contains the authentication for accessing the AD "database" the currently logged in user is authenticated against AD the way this has been set up and explained. We use that at our organization.
    – LReeder14
    Jul 6, 2018 at 16:12
12

Here's a solution from the tutorial Chris Schiffhauer - Implement Active Directory Authentication in ASP.NET MVC 5:

You can secure your MVC web application on an Active Directory network by authenticating users directly against their domain credentials.

STEP 1: ACCOUNTCONTROLLER.CS

Replace your AccountController.cs file with the following:

using System.Web.Mvc;
using System.Web.Security;
using MvcApplication.Models;

public class AccountController : Controller
{
    public ActionResult Login()
    {
        return this.View();
    }

    [HttpPost]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (!this.ModelState.IsValid)
        {
            return this.View(model);
        }

        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            if (this.Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return this.Redirect(returnUrl);
            }

            return this.RedirectToAction("Index", "Home");
        }

        this.ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");

        return this.View(model);
    }

    public ActionResult LogOff()
    {
        FormsAuthentication.SignOut();

        return this.RedirectToAction("Index", "Home");
    }
}

STEP 2: ACCOUNTVIEWMODELS.CS

Update your AccountViewModels.cs (or whatever your Account model class is named) to contain only this LoginModel class:

using System.ComponentModel.DataAnnotations;

public class LoginModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

STEP 3: WEB.CONFIG

Finally, update your Web.config file to include these elements.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
      <authentication mode="Forms">
          <forms name=".ADAuthCookie" loginUrl="~/Account/Login" timeout="45" slidingExpiration="false" protection="All" />
      </authentication>
      <membership defaultProvider="ADMembershipProvider">
          <providers>
              <clear />
              <add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" />
          </providers>
      </membership>
  </system.web>
  <connectionStrings>
      <add name="ADConnectionString" connectionString="LDAP://primary.mydomain.local:389/DC=MyDomain,DC=Local" />
  </connectionStrings>
</configuration>

It may take a few steps to get your LDAP connection string:

  1. Install Remote Server Administration Tools for Windows 7. Be sure the follow the post-installation instructions to add the feature to Windows via the control panel.

  2. Open a command prompt and enter >dsquery server

    Let’s say the command returns the following:

    CN=PRIMARY,CN=Servers,CN=DefaultFirstName,CN=Sites,CN=Configuration,DC=MyDomain,DC=Local
    
    • The server name is composed of the first CN value, and the two last DC values, separated by dots. So it's primary.mydomain.local.

    • The port is 389.

    • The portion of the connection string after the port and forward slash is the portion of the result beginning with the first "DC". So it's DC=MyDomain,DC=Local.

    • So the full connection string is

      LDAP://primary.mydomain.local:389/DC=MyDomain,DC=Local.
      
    • Users will login using just their username without the domain. So the correct username is Chris, not MYDOMAIN\Chris.

5
  • 1
    The link is dead (404)
    – Jonas
    Sep 20, 2017 at 18:06
  • dsquery server gives me 3 CN=PRIMARY01, CN=PRIMARY02 and CN=PRIMARY03 ? Which use ?
    – Kiquenet
    Nov 29, 2018 at 13:06
  • Windows Authentication, not Forms Authentication?
    – Kiquenet
    Nov 29, 2018 at 14:42
  • This works with me with Windows 10 also, but post need to change as "Install Remote Server Administration Tools for Windows 7 Server OS"
    – Kelum
    Dec 29, 2018 at 1:52
  • I've tried this, but even though the cookie is set, I keep getting redirected back to the login page. So frustrating.
    – Kev
    Mar 19, 2021 at 15:28
1

I found this link that checks against AD Security Groups:

Active Directory Authentication in ASP.NET MVC 5 with Forms Authentication and Group-Based Authorization

Only thing is this setup uses a login in page to capture the username/password credentials for AD. I changed the authentication from "FORMS" to "WINDOWS" since my app will always be accessed from within the network. Also don't forget to remove the <forms> sub-tag from the <authentication> tag if you are not going to use the FORMS authentication.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.