Search code examples
c#ldapuserinfo

LDAP and ActiveDirectory authentication in C#


I am new to LDAP and active directory authentication , I just studied few things about LDAp authentication and done with sample application

I just checking Does the user exist in ActiveDirectory or not

public static bool DoesUserExist()
  {
  using (var domainContext = new PrincipalContext(ContextType.Domain,Environment.UserDomainName))
   {
     using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, Environment.UserName))
                {
                    return foundUser != null;
                }
            }
        }

in our local system its working fine , But when i hosted in ActiveDirectory Server and i am trying to access this with server IP address, i am facing some issue like

ContextType.Domain,Environment.UserDomainName and  Environment.UserName

for these three values are coming from server Information not the users who accessing this application

So please help me how to get the User information(who accessing this application) so that i need to pass those info to server and need check for user is activedirectory user or not


Solution

  • Environment.UserDomainName returns the domain part of Environment.UserName, e.g. "mydomain.com", so you don't want that.

    Environment.UserName itself will return the user who is currently "logged in to Windows", i.e. the app pool user - see MSDN.

    You are better off checking the identity of the current web request, so in a MVC Controller or WebForms Page, use this.User.

    Or if you are using Windows Authentication or hooking Forms Authentication into AD, the current Thread Principal should be the current request user, so you can use Thread.CurrentPrincipal.Identity.