Example #1
0
 private static string GetDN(string Email)
 {
     try
     {
         System.DirectoryServices.AccountManagement.PrincipalContext  adContext = EstablishConnection();
         System.DirectoryServices.AccountManagement.PrincipalSearcher searcher  = new System.DirectoryServices.AccountManagement.PrincipalSearcher();
         UserPrincipalEx findUser = new UserPrincipalEx(adContext);
         findUser.EmailAddress = Email;
         searcher.QueryFilter  = findUser;
         UserPrincipalEx foundUser = (UserPrincipalEx)searcher.FindOne();
         if (foundUser != null)
         {
             using (DirectoryEntry baseEntry = foundUser.GetUnderlyingObject() as DirectoryEntry)
             {
                 using (DirectoryEntry entry = new DirectoryEntry(baseEntry.Path, baseEntry.Username, Password))
                 {
                     return((string)entry.Properties["distinguishedName"].Value);
                 }
             }
         }
         return(null);
     }
     catch (Exception e)
     {
         log.Error("Error while fetching DN of user '" + Email + "' from AD " + e.StackTrace);
         return(e.Message);
     }
 }
Example #2
0
        /// <summary>
        /// Authenticates the user
        /// </summary>
        /// <param name="CompanyID">Company ID</param>
        /// <param name="UserID">User ID</param>
        /// <param name="Password">Password</param>
        /// <returns>True if authenticated successfully</returns>
        public bool AuthenticateUser(string CompanyID, string UserID, string Password)
        {
            bool boolReturn = false;

            boolReturn = (from user in dataConn.Users
                          where (user.UserID == UserID && user.Password == Password) || (user.UserID == UserID && user.IgnorePassword == true)
                          select user).Count() > 0;

            if (boolReturn == false && dataConn.Users.Count(user => user.UserID == UserID) > 0)
            {
                using (System.DirectoryServices.AccountManagement.PrincipalContext pContext = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain))
                {
                    boolReturn = pContext.ValidateCredentials(UserID, Password);

                    if (boolReturn)
                    {
                        var varUser = (from usr in dataConn.Users where usr.UserID == UserID select usr).First();
                        varUser.Password = Password;
                        dataConn.SaveChanges();
                    }
                }
            }

            return boolReturn;
        }
Example #3
0
        /// <summary>
        /// Delete a local user with given name.
        /// </summary>
        /// It also deletes the local user folder and the profile in the
        /// registry.
        /// <param name="username">User name.</param>
        /// <returns>True if the user could be deleted successfully, false
        ///     otherwise.</returns>
        public static bool DeleteUser(string username)
        {
            using (var ctx = new System.DirectoryServices.AccountManagement.PrincipalContext(
                       System.DirectoryServices.AccountManagement.ContextType.Machine))
            {
                using (var up = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(
                           ctx,
                           System.DirectoryServices.AccountManagement.IdentityType.SamAccountName, username))
                {
                    if (up != null)
                    {
                        // User SID
                        string upSid = up.Sid.ToString();

                        // Delete the user
                        up.Delete();

                        // Delete the info from the registry
                        NativeMethods.DeleteProfile(upSid, null, null);

                        // Done
                        return(true);
                    }

                    // User not found
                    return(false);
                }
            }
        }
        }         // End Function GetProcessUser

        public static void AddImpersonatedToGroup()
        {
            try
            {
                using (System.DirectoryServices.AccountManagement.PrincipalContext pcLocal =
                           new System.DirectoryServices.AccountManagement.PrincipalContext(
                               System.DirectoryServices.AccountManagement.ContextType.Machine
                               )
                       )
                {
                    System.DirectoryServices.AccountManagement.GroupPrincipal group =
                        System.DirectoryServices.AccountManagement.GroupPrincipal
                        .FindByIdentity(pcLocal, "Administratoren")
                    ;

                    System.Console.WriteLine(group.DistinguishedName);

                    using (System.DirectoryServices.AccountManagement.PrincipalContext pcDomain
                               = new System.DirectoryServices.AccountManagement.PrincipalContext(
                                     System.DirectoryServices.AccountManagement.ContextType.Domain, "COMPANY") // "AAA"
                               )
                    {
                        group.Members.Add(pcDomain, System.DirectoryServices.AccountManagement.IdentityType.SamAccountName, "firstname.lastname");
                        group.Save();
                    };
                };
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine(e.Message);
            }
        } // End Function AddImpersonatedToGroup
Example #5
0
        public bool DomainLogin(string pLogin, string pPassWord)
        {
#pragma warning disable CA1416 // Validate platform compatibility
            System.DirectoryServices.AccountManagement.PrincipalContext prCont = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, "Vopak");
            return(prCont.ValidateCredentials(pLogin, pPassWord));

#pragma warning restore CA1416 // Validate platform compatibility
        }
Example #6
0
        public static bool UpdateUserInfo()
        {
            try
            {
                string domain = GetFqd((!string.IsNullOrEmpty(_UserName) && _UserName.Contains("\\") ? _UserName.Split('\\')[0] : string.Empty));
                using (System.DirectoryServices.AccountManagement.PrincipalContext ctx = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, domain))
                {
                    // ReSharper disable once UnusedVariable
                    bool val = ctx.ValidateCredentials(null, null, System.DirectoryServices.AccountManagement.ContextOptions.Negotiate);
                    using (System.DirectoryServices.AccountManagement.UserPrincipal up = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(ctx, _UserName))
                    {
                        // ReSharper disable once UnusedVariable
                        if (up != null)
                        {
                            using (System.DirectoryServices.DirectoryEntry de =
                                       (System.DirectoryServices.DirectoryEntry)up.GetUnderlyingObject())
                            {
                                //string adProperty = "";
                                //if (!de.Properties.Contains(adProperty))
                                //{
                                //    throw new Exception(String.Format("Property {0} does not exist for user {1}", adProperty, userID.Name));
                                //}
                                //switch(adProperty.ToLower()) {
                                //    case "accountexpires":
                                //    case "badpasswordtime":
                                //    case "lastlogon":
                                //    case "pwlastset":
                                //    case "whencreated":  //examples of AD date fields
                                //        DateTime adVal = SDHelpers.ADHelper.FromADDate(de.Properties[adProperty].Value);
                                //        //example of setting an AD Date value
                                //        //de.Properties[adProperty].Value = SDHelpers.ADHelper.ToADDate(DateTime.FromFileTimeUtc(0)); //0 for never(1 / 1 / 1601)-- i.e. for account expiration
                                //        //de.Properties[adProperty].Value = SDHelpers.ADHelper.ToADDate(DateTime.Now.AddMonths(3));   //actual date value
                                //        break;
                                //    case "objectguid":  //example of binary array (GUID) values
                                //        string adVal = SDHelpers.ADHelper.FromBinaryArray((byte[])de.Properties[adProperty].Value);   //equivilent to SDHelpers.ADHelper.FromBinaryArray(de.Properties(adProperty).Value, True)
                                //        //for no hypens
                                //        //string adVal = SDHelpers.ADHelper.FromBinaryArray((byte[])de.Properties[adProperty].Value, false);
                                //        break;
                                //    default:
                                //        string adVal = (string)de.Properties[adProperty].Value;
                                //        //example of setting an AD value
                                //        //de.Properties[adProperty].Value = "somevalue";
                                //        break;
                                //}
                                //  de.CommitChanges();   //save the changes
                                return(true);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                return(false);   //error creating the windowidentity object -- not a valid user
            }

            return(false);
        }
Example #7
0
 public static bool Validate_Principal(string userName, string pwd, string domain)
 {
     using (var pc = new System.DirectoryServices.AccountManagement
                     .PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, domain))
     {
         // validate the credentials
         return(pc.ValidateCredentials(userName, pwd));
     }
 }
Example #8
0
 static void Main(string[] args)
 {
     using (var context = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain))
     {
         using (var user = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(context, System.DirectoryServices.AccountManagement.IdentityType.SamAccountName, "DOMAIN\\user"))
         {
             user.ChangePassword("oldpassword", "newpassword");
             user.Save();
         }
     }
 }
Example #9
0
 private bool ValidateCredentials(string userName, string pwd)
 {
     if (NoPwdCheck)
     {
         return(true);
     }
     using (var pc = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, Domain))
     {
         // validate the credentials
         return(pc.ValidateCredentials(userName, pwd));
     }
 }
Example #10
0
 /// <summary>
 /// Check if a local user with given name exists.
 /// </summary>
 /// <param name="username">User name.</param>
 /// <returns>True if the user exists on the local machine, false
 ///     otherwise.</returns>
 public static bool UserExists(string username)
 {
     using (var ctx = new System.DirectoryServices.AccountManagement.PrincipalContext(
                System.DirectoryServices.AccountManagement.ContextType.Machine))
     {
         using (var up = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(
                    ctx,
                    System.DirectoryServices.AccountManagement.IdentityType.SamAccountName, username))
         {
             return(up != null);
         }
     }
 }
Example #11
0
        public static int Search(Person person)
        {
            int            success   = 200;
            int            error     = 404;
            int            exception = 415;
            String         path      = "LDAP://" + Hostname + "/" + BaseDN;;
            String         username  = Username;
            String         password  = Password;
            DirectoryEntry baseEntry = new DirectoryEntry(path, username, password);

            try
            {
                if (person.email == null)
                {
                    log.Error("Exception in search user. User email is null");
                    return(exception);
                }
                System.DirectoryServices.AccountManagement.PrincipalContext adContext = EstablishConnection();
                if (adContext != null)
                {
                    using (adContext)
                    {
                        DirectorySearcher dirSearcher = new DirectorySearcher(baseEntry);
                        dirSearcher.Filter      = "(&(objectClass=person))";
                        dirSearcher.SearchScope = SearchScope.Subtree;

                        SearchResultCollection results = dirSearcher.FindAll();

                        for (int i = 0; i < results.Count; i++)
                        {
                            DirectoryEntry entry     = results[i].GetDirectoryEntry();
                            String         mailValue = (string)entry.Properties["mail"].Value;
                            if ((mailValue != null) && mailValue.Equals(person.email))
                            {
                                log.Info("User found in AD '" + person.email + "'");
                                return(success);
                            }
                        }
                        log.Info("User not found in AD '" + person.email + "'");
                        return(error);
                    }
                }
                return(0);
            }
            catch (Exception e)
            {
                log.Info("Exception in search user '" + person.email + "' " + e.StackTrace);
                return(e.HResult);
            }
        }
Example #12
0
        private string GetUserFullName()
        {
            string fullName = "NA";

            using (var context = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain))
            {
                var principal = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(context, User.Identity.Name);
                if (principal != null)
                {
                    fullName = string.Format("{0} {1}", principal.GivenName, principal.Surname);
                }
            }

            return(fullName);
        }
Example #13
0
 private static System.DirectoryServices.AccountManagement.PrincipalContext EstablishConnection()
 {
     try
     {
         System.DirectoryServices.AccountManagement.PrincipalContext adContext = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, Hostname, BaseDN, @Username, Password);
         Boolean result = adContext.ValidateCredentials(Username, Password);
         if (result)
         {
             log.Info("Successfully Established connection to AD '" + Hostname + "' with username '" + Username + "'");
             return(adContext);
         }
         return(null);
     }
     catch (Exception e)
     {
         log.Error("Exception in Establish Connection to AD '" + Hostname + "' with username '" + Username + "'");
         Console.Write("\nError in establish connection: " + e.Message);
         throw new Exception();
     }
 }
    public static bool Authenticate(string user_, string password_)
    {
      bool ret;
      try
      {
        using (var pc = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, DOMAIN))
        {
          ret = pc.ValidateCredentials(user_, password_);
        }

        if (ret)
          UserName = user_.ToLower();
      }
      catch (Exception ex_)
      {
        Logger.Error("Error trying to authenticate user", typeof (SymmetryEnvironment), ex_);
        ret = false;
      }

      return ret;
    }
Example #15
0
        public bool            validatePassword()
        {
            string domainName;
            string userName;

            int i = AccountName.IndexOf('\\');

            if (i >= 0)
            {
                domainName = AccountName.Substring(0, i);
                userName   = AccountName.Substring(i + 1);
            }
            else
            {
                domainName = null;
                userName   = AccountName;
            }

            using (System.DirectoryServices.AccountManagement.PrincipalContext pc = new System.DirectoryServices.AccountManagement.PrincipalContext(domainName != null ? System.DirectoryServices.AccountManagement.ContextType.Domain : System.DirectoryServices.AccountManagement.ContextType.Machine, domainName))
                return(pc.ValidateCredentials(userName, AccountPassword));
        }
 public GroupPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context, string samAccountName)
 {
 }
 public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult <System.DirectoryServices.AccountManagement.ComputerPrincipal> FindByPasswordSetTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type)
 {
     throw null;
 }
 public GroupPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context)
 {
 }
 public ComputerPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context, string samAccountName, string password, bool enabled) : base(default(System.DirectoryServices.AccountManagement.PrincipalContext))
 {
 }
 public static new System.DirectoryServices.AccountManagement.ComputerPrincipal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue)
 {
     throw null;
 }
Example #21
0
 private bool Validate_User(string username, string password)
 {
     bool valid = false;
     using (System.DirectoryServices.AccountManagement.PrincipalContext context = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain))
     {
         valid = context.ValidateCredentials(username, password);
     }
     return valid;
 }
 public System.DirectoryServices.AccountManagement.PrincipalSearchResult <System.DirectoryServices.AccountManagement.Principal> GetGroups(System.DirectoryServices.AccountManagement.PrincipalContext contextToQuery)
 {
     throw null;
 }
 public static System.DirectoryServices.AccountManagement.Principal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, string identityValue)
 {
     throw null;
 }
 protected internal AuthenticablePrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context)
 {
 }
 public void Add(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue)
 {
 }
 protected internal AuthenticablePrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context, string samAccountName, string password, bool enabled)
 {
 }
 public static System.DirectoryServices.AccountManagement.PrincipalSearchResult <System.DirectoryServices.AccountManagement.AuthenticablePrincipal> FindByLogonTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type)
 {
     throw null;
 }
 protected static System.DirectoryServices.AccountManagement.Principal FindByIdentityWithType(System.DirectoryServices.AccountManagement.PrincipalContext context, System.Type principalType, string identityValue)
 {
     throw null;
 }
 protected static System.DirectoryServices.AccountManagement.PrincipalSearchResult <T> FindByPasswordSetTime <T>(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type)
 {
     throw null;
 }
 public void Save(System.DirectoryServices.AccountManagement.PrincipalContext context)
 {
 }
 public ComputerPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context) : base(default(System.DirectoryServices.AccountManagement.PrincipalContext))
 {
 }
 public bool Remove(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue)
 {
     throw null;
 }
 public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult <System.DirectoryServices.AccountManagement.UserPrincipal> FindByExpirationTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type)
 {
     throw null;
 }