Click here to Skip to main content
Click here to Skip to main content
Go to top

Authorize and authenticate users with AD

, 18 Nov 2004
Rate this:
Please Sign up or sign in to vote.
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.

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:

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).

[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:

<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)

Share

About the Author

Leonardo Pessoa
Software Developer
Brazil Brazil
I'm that strange type, who likes to code (mostly Objective-C and Javascript nowadays) and hates to use a database (I'd rather code one, instead!). I'm mainly interested in programming languages, compilers, interpreters and the like.
 
Although I don't place any form of restriction upon using the codes I provide, I would appreciate to be mentioned as it's author in any projects using them.
Follow on   Twitter   Google+

Comments and Discussions

 
Questionregarding authentication tools Pinmemberkailasapu murali4-Jun-13 19:22 
QuestionHow to get Windows Identity PinmemberMember 72740730-Nov-09 12:07 
AnswerRe: How to get Windows Identity PinmemberHarkos1-Dec-09 0:08 
GeneralRe: How to get Windows Identity PinmemberMember 7274071-Dec-09 4:02 
Generalldap java PinmemberNaciye2-Jul-08 4:15 
AnswerRe: ldap java PinmemberHarkos2-Jul-08 10:13 
GeneralRe: ldap java PinmemberNaciye2-Jul-08 21:13 
QuestionHow to use the source code? PinmemberJason Law27-Nov-07 19:09 
QuestionFailing to authenticate PinmemberBogo Mip22-Feb-07 15:02 
AnswerRe: Failing to authenticate PinmemberHarkos22-Feb-07 23:56 
Hi Nathan,
 
As I said before right here, I'm not an AD expert. I'm a little bit far from working with .NET too, but I'll try to provide you with some ground to solve your problem.
 
I really don't remember trying to authenticate another user the myself on a desktop app. But it seems to me the COM component used by .NET to access active directories depends on the account used run the app. I.E., on web applications, the account might have more access to AD than your normal user (this might be a built-in setting).
 
So, since you're asking for username and password, you could try impersonation. By using impersonation, your application behaves as if you run it with another user. Thus, impersonating the user whose AD account you want to connect to, might not only solve this problem. I'm affraid I never tried impersonation before, but you can easily find another article here on CodeProject.
 
Give it a try and let me know the results.
 
[]'s
Harkos
---
"Money isn't our god, integrity will free our soul."
Cut Throat - Sepultura

GeneralExtranet Pinmemberdave at b22-Nov-06 6:34 
GeneralRe: Extranet Pinmemberdave at b22-Nov-06 6:35 
AnswerRe: Extranet PinmemberHarkos23-Nov-06 0:16 
GeneralMethod LogonValid Pinmemberstancrm3-Nov-06 3:34 
GeneralRe: Method LogonValid PinmemberHarkos3-Nov-06 10:47 
Generalnewbie in ldap PinmemberLouPadrino24-Jul-06 23:33 
AnswerRe: newbie in ldap [modified] PinmemberHarkos25-Jul-06 2:47 
GeneralRe: newbie in ldap PinmemberLouPadrino25-Jul-06 3:24 
GeneralObject O PinmemberJames Curran13-Jun-06 12:51 
AnswerRe: Object O PinmemberHarkos14-Jun-06 1:21 
QuestionHow to get results from command "net session" using C#? PinmemberPi po10-Apr-06 18:15 
AnswerRe: How to get results from command "net session" using C#? PinmemberHarkos20-Apr-06 2:40 
GeneralSecurity accessing AD/LDAP PinmemberHarkos15-Sep-05 2:38 
GeneralCreate user on remote IIS server via LDAP Pinmemberdragomir14-Sep-05 8:02 
GeneralRe: Create user on remote IIS server via LDAP PinmemberHarkos15-Sep-05 2:19 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 18 Nov 2004
Article Copyright 2004 by Leonardo Pessoa
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid