Search code examples
c#asp.net.netdirectoryservices

.Net Directory services for local authentication


I am using directory services in .Net for first time.I want to use it to authenticate against local users on my machine in an asp.net website application The code is as follows

DirectoryEntry entry = new DirectoryEntry("WinNT://"+Environment.MachineName+"/administrator", txtBoxUserName.Text, txtBoxPWD.Text);

For some reason I get an exception of "System.Runtime.InteropServices.COMException" although I used the right user name and password for administrator user.

Any Help would be appreciated


Solution

  • Try this:

    
    public bool IsAuthenticationValid(string userName, string password)
    {
        using (var context = new PrincipalContext(ContextType.Machine))
        {
            return context.ValidateCredentials(userName, password);
        }
    }
    

    Edit: Forgot to mention you will need System.DirectoryServices and System.DirectoryServices.AccountManagement references.

    If you hit the same error, please describe what environment you are running this code in. By that I mean command line, web app, etc. Just some more background to see if I can help you further.