Apps

Active Directory authentication in .NET solves one BYOD challenge

Justin James presents two code samples that show how easy .NET makes it to authenticate against Active Directory.

One of the challenges with BYOD (bring your own device) for enterprise developers is authentication. In an environment of corporate-controlled devices, you can ensure that all of the devices play nicely with the IT department's systems of choice, which is usually Active Directory. Fortunately, .NET makes it easy to authenticate against Active Directory, which you can use in a Web service to let your mobile applications use for the "heavy lifting." It is also easy to query Active Directory.

Code sample A shows how to validate a user's credentials. Code sample B shows a basic Active Directory query. Code sample A needs a reference and a namespace reference to System.DirectoryServices.AccountManagement; code sample B needs the same for System.DirectoryServices. In code sample B, try an Active Directory path like this: "LDAP://DC=titaniumcrowbar,DC=com". Code sample A
private static bool UserLoggedIn(string Domain, string Username, string Password)
{
  var context = new PrincipalContext(ContextType.Domain, Domain);
  var result = context.ValidateCredentials(Username, Password);
  context.Dispose();
  return result;
}
Code sample B
private static bool ADQuery(string ActiveDirectoryPath, string Domain, string Username, string Password) {
  var dirEntry = new DirectoryEntry(ActiveDirectoryPath, Domain + @"\" + Username, Password);
   var nativeObject = dirEntry.NativeObject;
   var dirSearch = new DirectorySearcher(dirEntry);
   dirSearch.Filter = "(SAMAccountName=" + Username + ")";
   dirSearch.PropertiesToLoad.Add("cn");
   return dirSearch.FindOne() != null;
}

J.Ja

Additional BYOD resources

For more on this topic, check out the ZDNet and TechRepublic special feature BYOD and the Consumerization of IT, the TechRepublic Pro BYOD policy download, and The Executive's Guide to BYOD and the Consumerization of IT.

Keep your engineering skills up to date by signing up for TechRepublic's free Software Engineer newsletter, delivered each Tuesday.

About

Justin James is the Lead Architect for Conigent.

1 comments
jmy_hrt
jmy_hrt

using System.DirectoryServices.AccountManagement; neds to be included and the reference added to the project for this code to work. JamesH

Editor's Picks