Wednesday, March 16, 2011

Active Directory Authentication Asp.net

Very offen in web development, we come across a requirement where we need to use Active Directory Authentication in Asp.net; i .e. we need to use Active Directory to Authenticate user. The flow for the same can be assumed as following point. In this case we shall not have User table in Database unless required, we can verify the Authenticity of user with Active Directory.
  1. User logs in with Active Directoyl Login and Password.
  2. System verifies Login and Password with Active Directory
  3. If we get Success we will proceed the login else will display error.

We shall use following C# class naming AuthenticateUser to implement ActiveDirectory Authentication in Asp.net

public class AuthenticateUser
{
    public AuthenticateUser()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    private string _path;
    private string _filterAttribute;

    public AuthenticateUser(string path)
    {
        _path = path;
    }

    public bool IsAuthenticated(string domain, string username, string pwd)
    {
        string domainAndUsername = domain + @"\" + username;
        DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

        try
        {
            //Bind to the native AdsObject to force authentication.
            object obj = entry.NativeObject;

            DirectorySearcher search = new DirectorySearcher(entry);

            search.Filter = "(SAMAccountName=" + username + ")";
            search.PropertiesToLoad.Add("cn");
            SearchResult result = search.FindOne();

            if (null == result)
            {
                return false;
            }

            //Update the new path to the user in the directory.
            _path = result.Path;
            _filterAttribute = (string)result.Properties["cn"][0];
        }
        catch (Exception ex)
        {
            throw new Exception("Error authenticating user. " + ex.Message);
        }

        return true;
    }


}

Remeber we have added "System.DirectoryServices" name space.

We can simply use following code to Authenticate user using ActiveDirectory in asp.net

Note: In following code we use Authentication on Page Load event, you can implement this on Login Page.

protected void Page_Load(object sender, EventArgs e)
    {
        AuthenticateUser cls = new AuthenticateUser("LDAP://YourActiveDirectoryPath"); //Set Active Directory Path
        bool flag = cls.IsAuthenticated("ZESTORMTPL", "UserLoginID", "Password");
        //Put your UserLoginID and Password
    }
Active Directory Authentication Asp.net is as simple as copy pasting above code and use it as it is.
Submit this story to DotNetKicks

Read more...