Click here to Skip to main content
15,883,749 members
Articles / Programming Languages / C#
Article

Authorize and authenticate users with AD

Rate me:
Please Sign up or sign in to vote.
4.60/5 (29 votes)
18 Nov 2004CPOL3 min read 217.3K   2.1K   108   44
How much time do you spend to ensure user permissions? Ease the job and let Windows and Active Directory do it for you.

Introduction

I always had interest in security issues, specially about application use security. I believe user authentication and authorization is one of the main thoughts in application development (even if not the first to be coded).

Despite all my interest, just recently, I got the time to study the resources and advantages .NET offers to this matter. And there are many things I found.

Active Directory and LDAP

Since MS launched Windows 2000 family, there is the Active Directory (AD). Whoever has studied it is aware this is based on a less used Internet protocol called LDAP. Its job is, basically, manage users, groups and other security stuff on a domain in a simple way. The greater advantage is interoperability, since one can replace AD for another LDAP server given some work.

For developers, .NET comes with a full namespace to ease working with both AD and LDAP, System.DirectoryServices, which includes LDAP v3. On the following samples, I will use a fake domain called AD1.

C#
private static string domain = "AD1"; 

public static bool LogonValid(string userName, string password) {
  DirectoryEntry de = new DirectoryEntry(null, domain +
    "\\" + userName, password);
  try {
    object o = de.NativeObject;
    DirectorySearcher ds = new DirectorySearcher(de);
    ds.Filter = "samaccountname=" + userName;
    ds.PropertiesToLoad.Add("cn");
    SearchResult sr = ds.FindOne();
    if(sr == null) throw new Exception();
    return true;
  } catch {
    return false;
  }
}

public static bool IsInRole(string userName, string role) {
  try {
    role = role.ToLowerInvariant(); 
    DirectorySearcher ds = new DirectorySearcher(new DirectoryEntry(null));
    ds.Filter = "samaccountname=" + userName;
    SearchResult sr = ds.FindOne();
    DirectoryEntry de = sr.GetDirectoryEntry();
    PropertyValueCollection dir = de.Properties["memberOf"];
    for(int i = 0; i < dir.Count; ++i) {
      string s = dir[i].ToString().Substring(3);
      s = s.Substring(0, s.IndexOf(',')).ToLowerInvariant();
      if(s == role) return true;
    }
    throw new Exception();
  } catch {
    return false;
  }
}

These methods are implemented to work with a single application. The sources provided with this article are full implementations of IIdentity and IPrincipal interfaces. They are more suitable for developing ASP.NET Forms Authentication based on AD.

Let it to Windows

Applications can benefit more efficiently and easily from Active Directory by using another set of classes, also avoiding to create their own logon process. Developers should keep in mind this is a Windows-dependent solution.

But how is that possible? This time, we'll use Windows logon itself to authenticate the user, using only two classes in the System.Security.Principals namespace. Yet, this can be done in two ways:

C#
IIdentity wi = WindowsIdentity.GetCurrent();
IPrincipal wp = new WindowsPrincipal((WindowsIdentity)wi); 
// ...or... 
IPrincipal wp = Thread.CurrentPrincipal;
IIdentity wi = wp.Identity;

From now on, we can check if a user belongs to a user group by simply calling the method IsInRole defined by the IPrincipal interface. It's important to remember that domain groups must specify the domain (e.g. "AD1\Administrators"), or the group evaluated will belong to the machine running the code.

A call to IsInRole is an alternate when the group name is known only at runtime. Once it is known during design time, methods and even full classes can be blocked using PrincipalPermissionAttribute. This can allow access to specific groups (roles), users, or simply user is authenticated (remember, in Windows 9x/ME, the user can cancel logon).

C#
[PrincipalPermission(SecurityAction.Demand, Role="AD1\\Administrators")]

[PrincipalPermission(SecurityAction.Demand, User="AD1\\harkos")]

[PrincipalPermission(SecurityAction.Demand, Authenticated=true)]

The Windows identity can also be used to authenticate users on intranet sites. This configuration requires no code at all but adjusting the web.config file to the following lines:

XML
<authentication mode="Windows"/> 
<authorization>
   <allow roles="AD1\Administrators"/> 
</authorization>

<identity impersonate="true"/>

The last line is not mandatory, but it makes the ASP.NET process to impersonate the user accessing the site, thus making the site more secure and allowing the use of PrincipalPermissionAttributes through your ASP.NET code.

Conclusions

User authentication and authorization using Windows/Active Directory is the best way to protect applications running inside a corporation, like a webmail or ERP application, easing management and task delegation and avoiding multiple passwords. Of course, nothing here applies if users should or must not be associated with domain user accounts, like a blog or an event registration. In these cases, a larger implementation with or without databases is more suitable.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Brazil Brazil
architecture student (5/10)​ · designer · developer · geek

Comments and Discussions

 
GeneralRe: Create user on remote IIS server via LDAP Pin
Anonymous24-Sep-05 9:27
Anonymous24-Sep-05 9:27 
GeneralLoginvalid doesnt work in a workgroup Pin
Member 19357299-May-05 9:25
Member 19357299-May-05 9:25 
GeneralRe: Loginvalid doesnt work in a workgroup Pin
Leonardo Pessoa15-Sep-05 2:02
Leonardo Pessoa15-Sep-05 2:02 
GeneralTHANK YOU Pin
nsimeonov14-Apr-05 11:41
nsimeonov14-Apr-05 11:41 
GeneralAbout your IsInRole() method Pin
Pink Floyd6-Apr-05 13:37
Pink Floyd6-Apr-05 13:37 
GeneralRe: About your IsInRole() method Pin
Leonardo Pessoa15-Sep-05 1:54
Leonardo Pessoa15-Sep-05 1:54 
GeneralIUSR_&lt;servername&gt; Pin
wooboo4-Apr-05 21:16
wooboo4-Apr-05 21:16 
GeneralRe: IUSR_&lt;servername&gt; Pin
Leonardo Pessoa5-Apr-05 1:59
Leonardo Pessoa5-Apr-05 1:59 
GeneralGod damn Error!!! Pin
Pink Floyd1-Apr-05 11:58
Pink Floyd1-Apr-05 11:58 
GeneralRe: God damn Error!!! Pin
Leonardo Pessoa2-Apr-05 2:48
Leonardo Pessoa2-Apr-05 2:48 
QuestionAm I missing something? Pin
Pink Floyd31-Mar-05 12:00
Pink Floyd31-Mar-05 12:00 
AnswerRe: Am I missing something? Pin
Leonardo Pessoa1-Apr-05 7:00
Leonardo Pessoa1-Apr-05 7:00 
GeneralFrustration Pin
jou_ma_se_epos24-Feb-05 3:29
jou_ma_se_epos24-Feb-05 3:29 
GeneralRe: Frustration Pin
Leonardo Pessoa27-Feb-05 10:35
Leonardo Pessoa27-Feb-05 10:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.