June 10, 2009

Active Directory Authentication in C#

There is a lot of code on the web that actually does exactly what this post discusses. Also, in later versions of .NET, Microsoft almost gave the code outright to us. However, the issue with many versions on the web and even the approach Microsoft takes (with the ActiveDirectoryMembershipProvider) is that they do LDAP binds which is slower than making the Win32 call. What is the performance difference? Well, I ran a quick test and the results were than LogonUser was about 5x faster! I have uploaded my code here which is basked off an ILogin and a Win32 Login. The basic idea being that perhaps one day we move away from Active Directory Authentication. Here is the ILogin interface:
    public interface ILogin
{
void Authenticate(string username, string password);
void Authenticate(string username, string password, string domain);
}
The Win32 example is below:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using JL.Framework.Security;
using JL.Framework.Security.Win32Authentication;

namespace Console
{
class Program
{
static void Main(string[] args)
{
string username = "joe";
string password = "mypass";
string domain = "domain"; //note this is not required as I point out it can be called from a config

ILogin login = new Win32Login();
try{
login.Authenticate(username, password, domain);
System.Console.WriteLine("Successfully authenticated!");
}
catch (AuthenticationException ex)
{
System.Console.WriteLine(ex);
}

username = Win32Login.ParseLogonName("domainA\\userA", out domain);
Debug.Assert(username == "userA");
Debug.Assert(domain == "domainA");

username = Win32Login.ParseLogonName("userB@domainB", out domain);
Debug.Assert(username == "userB");
Debug.Assert(domain == "domainB");
}
}
}
You should be able to use the code in any authentication system you may have written in .NET that talks to AD.

No comments:

Post a Comment