Checking a User Exists in Active Directory

This isn’t a long post, but just a useful snippet of code. I was working on some code for a system this afternoon and I needed to check that a username was a valid user in ActiveDirectory using C#. This isn’t something I have had to code before, so I thought I would share this useful nugget of code. I hope you find it useful.

using System;
using System.Collections.Generic;
using System.Linq;
using System.DirectoryServices.AccountManagement;

namespace ActiveDirectory
{
    public static class ActiveDirectory
    {
        public static bool CheckUserinAD(string domain, string username)
        {
            using (var domainContext = new PrincipalContext(ContextType.Domain, domain))
            {
                using (var user = new UserPrincipal(domainContext))
                {
                    user.SamAccountName = username;

                    using (var pS = new PrincipalSearcher())
                    {
                        pS.QueryFilter = user;

                        using (PrincipalSearchResult<Principal> results = pS.FindAll())
                        {
                            if (results != null && results.Count() > 0)
                            {
                                return true;
                            }
                        }
                    }
                }
            }

            return false;
        }
    }
}
Participate with Coding in the Trenches on Facebook
Participate with Coding in the Trenches on Facebook by Click the button above.
Advertisements

Cryptography in .NET : Advanced Encryption Standard (AES)

I have released an Open Source libray under the GPL 3.0 license called Block Encrypter that builds on the code discussed in this article. If you need to do reliable and secure symmedtric encryption then this library would be very useful to you.

I thought I would start a little series on using some of the cryptography primitives in .NET. Cryptography and Encryption is something that most developers working on enterprise applications will come across, especially if you work in the financial services industry.

Advanced Encryption Standard (AES)
Advanced Encryption Standard (AES)

Whilst cryptography is a fascinating subject and the design of these algorithms is very interesting, I do not recommend using an algorithm that you have designed yourself. The standard algorithms in practice today have been through lots of analysis by experts both in private industry and governments all around the world trying to find faults and weaknesses, so you are much better off using these recommended systems.

The main algorithms fall into 2 categories, Symmetric encryption and Asymmetric encryption. Symmetric encryption contains algorithms that are based solely on an encryption key. For example, if you encrypt some plaintext with Key1 you get a cipher text out the other end. If you then decrypt the cipher text with the same key (Key1) you will get back to the original plaintext.

Asymmetric encryption works by having 2 keys, a public and private key. These keys are mathematically derived from each other. The public key can be used by anyone and the private key has to be kept secret. I will talk about asymmetric encryption and more specifically RSA in another post.

For this first article I am going to look at the AES symmetric algorithm. AES stands for the Advanced Encryption Standard. This was a competition winner when the National Institute of Standards and Technology ran a contest to replace the already broken DES algorithm.

What I will show in this article is a good practical implementation of AES in .NET. We will start with the following interface. The interface contains 2 methods, Encrypt and Decrypt. They methods take cipher text/plaintext and an encryption key.

using System;

namespace CryptoLibrary
{
    public interface IAES
    {
        string Decrypt(string ciphertext, string key);
        string Encrypt(string plainText, string key);
    }
}

Simple Dependency Injection

When you are working in the real world (especially on enterprise software) you will find yourself having to support and enhance an older code base. These code bases can vary quite considerably in quality. In the worst case you have legacy code that contains no unit tests. When you need to maintain and enhance this code you really should try to get some tests wrapped around the code, but this is easier said than done.

The code may contain lots of hard coded dependencies to objects that makes adding in clean, isolated unit tests difficult. These hard coded dependencies may access the file system, make database calls or access any other external resources making writing isolated tests difficult.

What do I mean by a hard coded dependency? Well, take a look at the following simple example.

using System;

namespace HardDependency
{
    public class ExampleClass
    {
        public string GetText
        {
            get
            {
                return "Hello, I am a hard dependency.";
            }
        }
    }

    public class MyProgram
    {
        public void DoSomething()
        {
            ExampleClass example = new ExampleClass();
            Console.WriteLine(example.GetText);
        }
    }

    class Program
    {
        static void Main()
        {
            MyProgram program = new MyProgram();
            program.DoSomething();
            Console.ReadLine();
        }
    }
}

In this simple example we have a class called ExampleClass. This class has a property that returns a string. The class MyProgram has a method called DoSomething() that creates an instance of ExampleClass and calls the property to display the returned string. You may be thinking that nothing untoward is happening here, but what you see here is an example of a hard dependency, or coupling, between MyProgram and ExampleClass. Lets imagine ExampleClass is doing something much more complicated like reading data from a database. If you try to write a unit test to cover the functionality¬† of the DoSomething() method in MyProgram then that unit test will be making a database call. This is not a unit test. It may run fine on your development PC, but when you try to run these unit tests on your build server, it will also try to make a call to the database. A build server shouldn’t have access to an applications database. Also, what if that call to the database changes the state of the data, so that the next time you run the test, the data has changed, so the test fails. This is not a good situation as you now not only have tight coupling in your code, but you are also coupled to the state of the data in your database.