CodeDigest.Com Logo
Featured:

Forms Authentication Using Active Directory Users in Asp.Net MVC (Without using Providers)

Tagged as: Asp.Net Asp.Net MVC Posted By

Sometimes, we may need to authenticate users against Active Directory when using Form Based authentication. Traditionally, we will enable Integrated Authentication in IIS and set Authentication mode as Windows in Web.Config file to authenticate users against Active Directory. This will enable the domain users to log into the application without explicitly specifying the username/password when accessed through Internet Explorer. This is because, Windows Integrated Authentication is enabled by default in IE, whereas the other non-Microsoft browsers like Firefox, Google Chrome, etc. it will pop up a login dialogue to input your domain username and password when using Windows Authentication.

Since, the usage of Non-Microsoft browsers has increased in every organization, it is better to provide a login screen(or Forms Authentication) to authenticate domain users too. Let’s see how to authenticate users against Active Directory by explicitly asking users to input username and password in a Asp.Net MVC application. The code discussed here will work in WebForms application too.

For Active Directory interaction, we will use an open source component called Galactic API.

Let’s create an Asp.Net MVC application in Visual Studio 2015(2013 or 2015) and select “Individual User Accounts” or “Internet Application” type to enable Forms Authentication by default.

Note- This article will not discuss on basics and configuring Forms Authentication in your project. We will use the default Forms Authentication configurations and code provided by Visual Studio and customize it to use AD.

First, let’s add Galactic API for Active Directory interaction in our project. To do this, right click your project in Solution explorer and Click Manage Nuget Packages...Search for “Galactic.ActiveDirectory” and click Install. This will install all the required components and dependent packages into our project.

Since, we have selected “Individual User Accounts” when creating our project, all configuration settings and a template Login/LogOff action methods for Forms Authentication will be created for us. Let’s change this code and authenticate users from Active Directory.

Logon Code:

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

[public ActionResult Login(LoginModel model, string returnUrl)

{

string serverName = ConfigurationManager.AppSettings["ADServer"];

if (ModelState.IsValid)

{

       SecureString securePwd = null;

       if (model.Password != null)

       {

              securePwd = new SecureString();

              foreach (char chr in model.Password.ToCharArray())

              {

                     securePwd.AppendChar(chr);

              }

       }

       try

       {

              //Check user credentials

              ActiveDirectory adVerifyUser = new ActiveDirectory(serverName, model.UserName, securePwd);

 

              FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

              return RedirectToLocal(returnUrl);

       }

       catch

       {

              // If we got this far, something failed, redisplay form

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

       }

}

 

return View(model);

}

 
 

Include Galactic.ActiveDirectory namespace for the above code to work and add the below AppSettings in Web.Config file. Get the AD server name of your company and paste it into the value field.

 

<add key="ADServer" value="[ADServerName.com]" />

 

 

Login View Model:

 

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; }

    } 

 

 

The above code(bolded under Logon Code section) will try to connect to AD server using the username and password provided by the user in Login screen. If the username and password combination is valid, it will create a Forms Authentication ticket and it will authenticate the user successfully. If the username and password combination is invalid, the catch block is executed and it will throw an error message “The user name or password provided is incorrect.”.

Download the source and see it in action.

Let’s build a user profile page and display user information fetched from Active Directory in the next article.



Feedback

Comments

Error - automatic authentication
After posting on [localIIS], I got a problem: automatic authentication. In the browser I have set: automatic login to the network with the current username and password. To solve the problem, you need in config.web: Under the tag system.web, changed authentication mode = "None" to authentication mode = "Windows" Under tag appSettings, added add key = "owin: AutomaticAppStartup" value = "false" Found a solution here: https://stackoverflow.com/questions/28483745/http-error-404-15-not-found-because-the-query-string-is-too-long
Commented by Alexey on 6/15/2020 12:49:59 AM

Connection
Unable to establish connection to Active Directory.
Commented by Abdulaziz on 5/18/2020 5:23:53 PM

Nice work!
Excellent article and example code. Using the Galactic package was the perfect approach. Thanks
Commented by Syntax Solutions on 12/16/2019 6:40:23 PM

How i can add user in active directory using this pattern and aslo how i can manage password in this pattern?
Is it possible in this way?
Commented by Fiaz on 2/12/2019 10:47:14 AM

logoncode
which page /file has logon code?
Commented by K Christian on 7/6/2018 11:48:07 AM