Today, we will explain you to implement LDAP Authentication in MVC application in very simple way and very small of coding. LDAP stands for Lightweight Directory Access Protocol. This method is use to prevent the user from direct access of other pages then Login page from URL.

So, let’s create MVC application and design as per your requirement:

Create a class with “ActionAuthorizeAttribute.cs” name in Model folder and paste below code in to it.

[AttributeUsage(AttributeTargets.All | AttributeTargets.Method, AllowMultiple =false, Inherited = true)]

publicclassActionAuthorizeAttribute : ActionFilterAttribute

{

publicoverridevoidOnActionExecuting(ActionExecutingContextfilterContext)

    {

string controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();

if (!controller.Equals(“account”))

        {

if (string.IsNullOrEmpty(HttpContext.Current.Session[“Username”].ToString())

||string.IsNullOrEmpty(HttpContext.Current.Session[“Password”].ToString()))

            {

                //send them off to the login page

varurl = newUrlHelper(filterContext.RequestContext);

string access = string.Empty;

access = “/Account/Login”;

varloginUrl = url.Content(access);

if (filterContext.HttpContext.Request.IsAjaxRequest())

                {

  1. filterContext.HttpContext.Response.Write(“<script>”);
  2. filterContext.HttpContext.Response.Write(“window.location.reload(‘” + loginUrl + “‘);”);
  3. filterContext.HttpContext.Response.Write(“</script>”);

                }

else

                {

varrouteValues = newRouteValueDictionary(new

                    {

action = “Login”,

controller = “Account”

                    });

  1. filterContext.Result = newRedirectToRouteResult(routeValues);

                }

            }

        }

  1. base.OnActionExecuting(filterContext);

    }

}

The above method fires on every Action call and compare the username and password with session value, if the user is not authorize or not logged in then this will send them to login page.


Also you have to update FilterConfig.csfile in App_Start folder as below.


publicstaticvoidRegisterGlobalFilters(GlobalFilterCollection filters)

       {

  1. filters.Add(newHandleErrorAttribute());
  2. filters.Add(newActionAuthorizeAttribute());

}


Now update login Action in Login Controller as below.


[HttpPost]

      [AllowAnonymous]

publicActionResult Login(LoginViewModel model, stringreturnUrl)

      {

if (!this.ModelState.IsValid)

          {

  1. returnthis.View(model);

          }

//Check LDAP Authentication

if (this.AuthenticateAD(model.Username, model.Password))

          {

//Save credentials to use while accessing reports.

Session[“Username”] = model.Username;

Session[“Password”] = model.Password;

  1. FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);

if (this.Url.IsLocalUrl(returnUrl) &&returnUrl.Length> 1 &&

  1. returnUrl.StartsWith(“/”)&& !returnUrl.StartsWith(“//”) &&

!returnUrl.StartsWith(“/\\”))

              {

  1. returnthis.Redirect(returnUrl);

              }

  1. returnthis.RedirectToAction(“Index”, “Home”);

          }

  1. this.ModelState.AddModelError(string.Empty, “The Username or Password is incorrect.”);
  2. returnthis.View(model);

}

Add following method to Login Controller.

publicboolAuthenticateAD(string username, string password)

{

using (var context = newPrincipalContext(ContextType.Domain,

  1. ConfigurationManager.AppSettings[“DomainName”]))

{

  1. returncontext.ValidateCredentials(username, password);

}

}


Set “DomainName” in webconfig file, here Domain Name always remains same so we can set hardcode in webconfig file. I set it like this.


<addkey=DomainNamevalue=MYEXAMPLE/>


Everytime you will see login screen if you are not logged in and try to access another controller direct from URL. e.g. myexample/Employee.

   sap 1.pngElse if you are authorized and your Username and Password are correct then you will redirect to Index page.
sap 2.png
So, now you know how to implement LDAP Authentication in asp.net MVC development. But if you have any doubt or couldn’t understand any step or code, just let the author know. You can comment and feedback for this post.

  Author of this post is sharing the steps to implement LDAP Authentication in asp.net MVC development. He is using an instance of MVC application and designing as per the requirement. Understand the process and learn the implementation of LDAP Authentication in MVC.

To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply