January 20, 2015

Helper Class in C# to Communicate with Active Directory(AD)

If you are using Microsoft Active Directory (AD) to create/manage/maintain users, you may have encountered this situation to ask AD about a user status or user information. As you may know, querying AD using C# is not as simple as it should be. To recognize that a user has been locked or expired and etc. it is better to create a Helper or Wrapper to map AD information to a C# class.

Especially in authentication and authorization sections of your application, accessing AD properties via a C# class can be really helpful and easily save your time.

UserDetails is the name of class that maintain all the AD information for specific user:

public class UserDetails
    public bool PasswordNeverExpired { get; set; }
    public bool IsAccountLocked { get; set; }
    public bool IsAccountActive { get; set; }
    public bool HasPasswordExpired { get; set; }
    public DateTime PasswordExpirationDate { get; set; }
    public DateTime PasswordLastChanged { get; set; }
    public bool ForceChangePassword { get; set; }
    public bool IsUserExist { get; set; }
    public bool IsAuthenticate { get; set; }

Following you can see the numbers of AD messages that are mapping to an UserStatus enumuration. 

525 user not found
52e invalid credentials
530 not permitted to logon at this time
531 not permitted to logon at this workstation
532 password expired
533 account disabled
701 account expired
773 user must reset password
775 user account locked

Below you can see the UserStatus enum which is available after loading user information from AD:

public enum UserStatus
    NotPermittedToLogonAtThisTime, //530
    NotPermittedToLogonAtThisWorkstation, //531
    PasswordExpired, //532
    AccountExpired, //701
    UserAccountLocked, //775

Downlaod Active Directory Helper Source Code from github