Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7129741
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T11:16:30+00:00 2026-05-28T11:16:30+00:00

in an .NET application, I’m trying to authenticate users by username and password a

  • 0

in an .NET application, I’m trying to authenticate users by username and password a against windows users, local ones as well as domain users. I already tried this solution . My code to get the PrincipalContext looks the following:

protected static PrincipalContext TryCreatePrincipalContext(String domain)
{
    var computerDomain = TryGetComputerDomain();

    if (String.IsNullOrEmpty(domain) && String.IsNullOrEmpty(computerDomain))
        return new PrincipalContext(ContextType.Machine);
    else if (String.IsNullOrEmpty(domain))
        return new PrincipalContext(ContextType.Domain, computerDomain);
    else
        return new PrincipalContext(ContextType.Domain, domain);
}

protected static String TryGetComputerDomain()
{
    try
    {
        var domain = Domain.GetComputerDomain();
        return domain.Name;
    } catch
    {
       return null;
    }
}

That works fine for local windows users users and for remote users in an ActiveDirectory. But if I try to run the authentication on a machine, that is joined to a non-ActiveDirectory Domain Master, eg. a Samba Server I get the following Exception:

System.DirectoryServices.AccountManagement.PrincipalServerDownException: Mit dem Server konnte keine Verbindung hergestellt werden. ---> 
System.DirectoryServices.Protocols.LdapException: Der LDAP-Server ist nicht verfügbar.
bei System.DirectoryServices.Protocols.LdapConnection.Connect()
bei System.DirectoryServices.Protocols.LdapConnection.SendRequestHelper(DirectoryRequest request, Int32& messageID)
bei System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request, TimeSpan requestTimeout)
bei System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request)
bei System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(String serverName, ServerProperties& properties)
--- Ende der internen Ausnahmestapelüberwachung ---
bei System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(String serverName, ServerProperties& properties)
bei System.DirectoryServices.AccountManagement.PrincipalContext.DoServerVerifyAndPropRetrieval()
bei System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType, String name, String container, ContextOptions options, String userName, String password)
bei System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType, String name)
bei DomainAuthTest.DomainAuthenticator.TryCreatePrincipalContext(String domain)
bei DomainAuthTest.DomainAuthenticator.Authenticate(String domainUser, String  password)
bei DomainAuthTest.Program.Main(String[] args)

So it seems that the PrincipalContext tries to use LDAP in case of ContextType.Domain. If I try to use ContextType.Machine I have cannot use the workgroup/domain-name as PrincipalContext tries to connect directly to the machine. That fails if there is already a connection to that machine with that windows from the same machine.

So my question is:

  • How to authenticate a user with the credentials domain, username and password against a domain master, which is not necessarily based on an ActiveDirectory?
  • Are there managed APIs to accomplish the above described task?
  • If there are no managed foundation-classes, what is the right direction to do that with?

Thank you for your replies.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T11:16:31+00:00Added an answer on May 28, 2026 at 11:16 am

    For the sake of completeness, here my solution which seems to do exactly what I want:

    public class WinApiDomainAuthenticator
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(string lpszUsername,
                                            string lpszDomain,
                                            string lpszPassword,
                                            int dwLogonType,
                                            int dwLogonProvider,
                                            out IntPtr phToken);
    
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);
    
        public static IPrincipal Authenticate(String domainUser, String password)
        {
            var userToken = IntPtr.Zero;
            var creds = new DomainAuthCredentials(domainUser, password); 
    
            if (! LogonUser(creds.Username, 
                            creds.Domain,
                            creds.Password,
                           (int)LogonType.LOGON32_LOGON_BATCH, 
                           (int)LogonProvider.LOGON32_PROVIDER_DEFAULT, out userToken))
            {
                var error = new Win32Exception(Marshal.GetLastWin32Error());
                throw new SecurityException("Error while authenticating user", error);
            }
    
            var identity = new WindowsIdentity(userToken);
    
            if (userToken != IntPtr.Zero) 
                CloseHandle(userToken);
    
            return ConvertWindowsIdentityToGenericPrincipal(identity);
        }
    
        protected static IPrincipal ConvertWindowsIdentityToGenericPrincipal(WindowsIdentity windowsIdentity)
        {
            if (windowsIdentity == null)
                return null;
    
            // Identity in format DOMAIN\Username
            var identity = new GenericIdentity(windowsIdentity.Name);
    
            var groupNames = new string[0];
            if (windowsIdentity.Groups != null)
            {
                // Array of Group-Names in format DOMAIN\Group
                groupNames = windowsIdentity.Groups
                                            .Select(gId => gId.Translate(typeof(NTAccount)))
                                            .Select(gNt => gNt.ToString())
                                            .ToArray();
            }
    
            var genericPrincipal = new GenericPrincipal(identity, groupNames);
            return genericPrincipal;
        }
    
        protected class DomainAuthCredentials
        {
            public DomainAuthCredentials(String domainUser, String password)
            {
                Username = domainUser;
                Password = password;
                Domain = ".";
    
                if (!domainUser.Contains(@"\"))
                    return;
    
                var tokens = domainUser.Split(new char[] { '\\' }, 2);
                Domain = tokens[0];
                Username = tokens[1];
            }
    
            public DomainAuthCredentials()
            {
                Domain = String.Empty;
            }
    
            #region Properties
    
            public String Domain { get; set; }
            public String Username { get; set; }
            public String Password { get; set; }
    
            #endregion
        }
    }
    

    The LogonType and LogonProvider enums reflect the definitions in “Winbase.h”. I settled with LogonType.LOGON32_LOGON_BATCH instead of LogonType.LOGON32_LOGON_NETWORK because samba 3.4.X seems to have trouble with this type.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an ASP.NET application that authenticates users using Ldap against active directory. This
I have an ASP.net Application that runs on the internal network (well, actually it's
Our .NET application controls measurement instruments. The application is installed and many different windows
am running the asp.net application...am enhancing the already developed project..i want to create the
net application, in which i am using some popup windows to open some pages.
I have an ASP.NET application that uses a custom MembershipProvider to allow users to
I have an ASP.Net application (on Win2K) that is using Windows authentication and impersonation.
I have an ASP.NET application which runs in Windows Server 2003. In this application
I have an ASP.NET application which runs fine on my local development machine. When
My .NET application fails when run from a network drive even when the very

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.