Search code examples
c#asp.netasp.net-mvcactive-directory

How to get user's password expiration date from Active Directory?


I have implemented implemented Active Directory authentication in ASP.NET MVC 5 using LDAP. I want to know how to get a user's

  1. Account Locked (boolean)
  2. Password Expired (boolean)
  3. Password Expiry Date (DateTime)

This is my current code:

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

[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");
}

Solution

  • I manage to do it using a combination of System.Web.Security and System.DirectoryServices.

    public bool IsExpired(MembershipUser user, LoginModel model)
    {
        bool result = false;
    
        string ldap = ConfigurationManager.ConnectionStrings["ADConnectionString"].ConnectionString;
    
        DirectoryEntry rootEntry = new DirectoryEntry(ldap, model.UserName, model.Password, AuthenticationTypes.Secure);
    
        DirectorySearcher mySearcher = new DirectorySearcher(rootEntry);
    
        SearchResultCollection results;
        string filter = "maxPwdAge=*";
        mySearcher.Filter = filter;
    
        results = mySearcher.FindAll();
        long maxDays = 0;
        if (results.Count >= 1)
        {
            Int64 maxPwdAge = (Int64)results[0].Properties["maxPwdAge"][0];
            maxDays = maxPwdAge / -864000000000;
        }
    
        long daysLeft = 0;
    
        daysLeft = maxDays - DateTime.Today.Subtract(user.LastPasswordChangedDate).Days;
    
        if (daysLeft <0)
        {
            result = true;
        } else
        {
            if (daysLeft<=14)
            {
                this.Expiring = true;
                this.ExpiringString = String.Format("You must change your password within" + " {0} days", daysLeft);
            }       
            else
            {
                this.Expiring = false;
            }     
        }
    
        return result;
    }