// Implement the overloaded search method FindByIdentity.
 public static new ContactPrincipal FindByIdentity(PrincipalContext context,
     string identityValue)
 {
     return (ContactPrincipal) FindByIdentityWithType(context,
         typeof (ContactPrincipal),
         identityValue);
 }
 public static new UserPrincipalFull FindByIdentity(PrincipalContext context,
     string identityValue)
 {
     return (UserPrincipalFull) FindByIdentityWithType(context,
         typeof (UserPrincipalFull),
         identityValue);
 }
 //work around way to create a new contact object
 public static ContactPrincipal CreateContact(PrincipalContext context, string name)
 {
     var ouDe = new DirectoryEntry();
     if (context.ContextType == ContextType.Domain)
     {
         ouDe = new DirectoryEntry(string.Format("LDAP://{0}", context.Container));
     }
     if (context.ContextType == ContextType.ApplicationDirectory)
     {
         ouDe = new DirectoryEntry(string.Format("LDAP://{0}/{1}", context.ConnectedServer, context.Container));
     }
     var contactDe = ouDe.Children.Add(String.Format("CN={0}", name), "contact");
     contactDe.CommitChanges();
     return FindByIdentity(context, name);
 }
Ejemplo n.º 4
0
        private void AddUser()
        {
            if (this.User == null)
            {
                Log.LogError("User is required");
                return;
            }

            PrincipalContext principalContext = null;
            UserPrincipal    userPrincipal    = null;

            try
            {
                bool isLocalMachineUser = string.IsNullOrEmpty(this.Domain) || string.Compare(this.Domain, this.MachineName, StringComparison.OrdinalIgnoreCase) == 0;
                principalContext = isLocalMachineUser ? new PrincipalContext(ContextType.Machine) : new PrincipalContext(ContextType.Domain);
                userPrincipal    = UserPrincipal.FindByIdentity(principalContext, this.User[0].ItemSpec);

                if (userPrincipal == null)
                {
                    this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Adding User: {0}", this.User[0].ItemSpec));
                    userPrincipal = new UserPrincipal(principalContext);
                }
                else
                {
                    this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Updating User: {0}", this.User[0].ItemSpec));
                }

                userPrincipal.SamAccountName       = this.User[0].ItemSpec;
                userPrincipal.DisplayName          = this.FullName;
                userPrincipal.Description          = this.Description;
                userPrincipal.PasswordNeverExpires = this.PasswordNeverExpires;
                userPrincipal.Enabled = true;
                if (this.PasswordExpired)
                {
                    userPrincipal.ExpirePasswordNow();
                }

                if (!string.IsNullOrEmpty(this.Password))
                {
                    userPrincipal.SetPassword(this.Password);
                }

                if (!isLocalMachineUser)
                {
                    string fullyQualifiedDomainName = GetFullyQualifiedDomainName();
                    userPrincipal.UserPrincipalName = !string.IsNullOrWhiteSpace(fullyQualifiedDomainName) ? this.User[0].ItemSpec + "@" + fullyQualifiedDomainName : this.User[0].ItemSpec;
                }

                userPrincipal.Save();

                if (!(string.IsNullOrWhiteSpace(this.FirstName) && string.IsNullOrWhiteSpace(this.LastName)))
                {
                    if (!isLocalMachineUser)
                    {
                        if (!string.IsNullOrWhiteSpace(this.FirstName))
                        {
                            userPrincipal.GivenName = this.FirstName;
                        }

                        if (!string.IsNullOrWhiteSpace(this.LastName))
                        {
                            userPrincipal.Surname = this.LastName;
                        }

                        userPrincipal.Save();
                    }
                    else
                    {
                        this.LogTaskWarning(string.Format(CultureInfo.CurrentCulture, "Cannot set First Name or Last Name for the user {0}. The operation is not supported for local users.", this.User[0].ItemSpec));
                    }
                }
            }
            finally
            {
                if (userPrincipal != null)
                {
                    userPrincipal.Dispose();
                }

                if (principalContext != null)
                {
                    principalContext.Dispose();
                }
            }
        }
Ejemplo n.º 5
0
 static public void LoadRazorAssemblies()
 {
     if (!_loadDone)
     {
         try
         {
             //Force the load of the assemblies
             if (dummy == null)
             {
                 dummy = new HtmlString("");
             }
             if (dummy2 == null)
             {
                 dummy2 = new DataTable();
                 dummy2.AsEnumerable();
             }
             if (dummy3 == null)
             {
                 dummy3 = new OleDbConnection();
             }
             if (dummy4 == null)
             {
                 dummy4 = new LdapConnection("");
             }
             if (dummy5 == null)
             {
                 dummy5 = new SyndicationFeed();
             }
             if (dummy6 == null)
             {
                 dummy6 = new XDocument();
             }
             if (dummy8 == null)
             {
                 dummy8 = new PrincipalContext(ContextType.Machine);
             }
             if (dummy9 == null)
             {
                 dummy9 = JWT.DefaultSettings;
             }
             if (dummy10 == null)
             {
                 dummy10 = JObject.Parse("{}");
             }
             if (dummy11 == null)
             {
                 dummy11 = new FastZip();
             }
             if (dummy12 == null)
             {
                 dummy12 = new OdbcConnection();
             }
             if (dummy13 == null)
             {
                 dummy13 = new SqlConnection();
             }
             if (dummy14 == null)
             {
                 dummy14 = new SftpClient("", "a", "");
             }
             if (dummy15 == null)
             {
                 dummy15 = new FtpClient();
             }
             if (dummy16 == null)
             {
                 dummy16 = new HttpClient();
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
         }
         _loadDone = true;
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Configures User Groups in Activity Directory for each user count..
        /// </summary>
        /// <param name="credential">The credential.</param>
        /// <param name="addToGroups">Whether to add the user to the AD groups specified in the manifest.</param>
        protected void ConfigureUserGroups(OfficeWorkerCredential credential, bool addToGroups = true)
        {
            if (credential == null)
            {
                throw new ArgumentNullException("credential");
            }

            string userName = credential.UserName;

            // Check to be sure there are user groups to configure
            string securityGroupXml = SystemManifest.Resources.GetByUsername(userName).SecurityGroups;

            if (string.IsNullOrEmpty(securityGroupXml))
            {
                // There are no active directory groups to process, so return
                return;
            }

            // Get the groups to be processed and the appropriate logging label
            Collection <ActiveDirectoryGroup> groups = null;
            string label = string.Empty;

            if (addToGroups)
            {
                groups = LegacySerializer.DeserializeDataContract <Collection <ActiveDirectoryGroup> >(securityGroupXml);
                label  = "Adding";
            }
            else
            {
                groups = new Collection <ActiveDirectoryGroup>();
                label  = "Removing";
            }

            PrincipalContext context = new PrincipalContext(ContextType.Domain);

            // Compare what the list of groups are to the master list from Active Directory
            // for every entry found in active directory add it to the list to be processed.
            // If there is a group listed to be assigned but it doesn't exist anymore in active
            // directory, log that error.
            var groupsToAssign = new List <GroupPrincipal>();

            if (addToGroups)
            {
                foreach (var group in groups)
                {
                    GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(context, group.Name);
                    if (groupPrincipal != null)
                    {
                        TraceFactory.Logger.Debug("Group {0} will be assigned to {1}".FormatWith(groupPrincipal.Name, credential.UserName));
                        groupsToAssign.Add(groupPrincipal);
                    }
                    else
                    {
                        TraceFactory.Logger.Error("The group {0} does not exist in the Active Directory server".FormatWith(group.Name));
                    }
                }
            }

            // Find any groups the user is a member of that must be removed.  Ignore Domain Users, since that group cannot be unjoined.
            UserPrincipal userPrincipal      = UserPrincipal.FindByIdentity(context, userName);
            var           existingUserGroups = userPrincipal.GetAuthorizationGroups().OfType <GroupPrincipal>();
            var           groupsToRemove     = existingUserGroups.Except(groupsToAssign).Where(n => n.Name != "Domain Users");

            Action action = () =>
            {
                ActiveDirectoryController.RemoveUserFromGroups(userPrincipal, groupsToRemove);
                ActiveDirectoryController.AddUserToGroups(userPrincipal, groupsToAssign);
            };

            try
            {
                Retry.WhileThrowing(action, 10, TimeSpan.FromSeconds(5), new List <Type> {
                    typeof(DirectoryServicesCOMException)
                });
            }
            catch (UnauthorizedAccessException)
            {
                TraceFactory.Logger.Debug("User {0} is not authorized to assign group membership. {1} will not be assigned."
                                          .FormatWith(Environment.UserName, credential.UserName));
            }
        }
Ejemplo n.º 7
0
 // Inplement the constructor using the base class constructor.
 public UserPrincipalEx(PrincipalContext context)
     : base(context)
 {
 }
Ejemplo n.º 8
0
        /// <summary>
        /// The get group.
        /// </summary>
        public static GroupPrincipal GetGroup(string groupName)
        {
            PrincipalContext principalContext = GetPrincipalContext;

            return(GroupPrincipal.FindByIdentity(principalContext, IdentityType.Name, groupName));
        }
Ejemplo n.º 9
0
 public AdCommon(string adDomain, string adContainer)
 {
     AdPrincipalContext = new PrincipalContext(ContextType.Domain, adDomain, adContainer);
 }
        public void ValidateCredentials_InvalidOptions_ThrowsArgumentException(ContextOptions options)
        {
            var context = new PrincipalContext(ContextType.Machine);

            AssertExtensions.Throws <ArgumentException>(null, () => context.ValidateCredentials("userName", "password", options));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// The get user.
        /// </summary>
        public static UserPrincipal GetUser(string samAccountName)
        {
            PrincipalContext principalContext = GetPrincipalContext;

            return(UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, samAccountName));
        }
Ejemplo n.º 12
0
 internal override Principal CreateExtendedPrincipal(PrincipalContext context, string name)
 {
     Assert.Inconclusive("TODO: Implement code to verify target");
     throw new System.NotImplementedException();
 }
        public void ValidateCredentials_IncorrectUserNamePassword_ThrowsException()
        {
            var context = new PrincipalContext(ContextType.Machine);

            Assert.Throws <Exception>(() => context.ValidateCredentials("userName", "password"));
        }
Ejemplo n.º 14
0
 internal override Principal CreatePrincipal(PrincipalContext context, string name)
 {
     return(new GroupPrincipal(context, name));
 }
Ejemplo n.º 15
0
 internal override Principal FindExtendedPrincipal(PrincipalContext context, string name)
 {
     throw new System.NotImplementedException();
 }
Ejemplo n.º 16
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (txtUsuario.Text == "" && txtSenha.Text == "")
            {
                MessageBox.Show("Um ou mais campos obrigatórios não foram informados\n\n*Usuário\n*Senha", "Falha no Login",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (txtUsuario.Text == "")
            {
                MessageBox.Show("Um ou mais campos obrigatórios não foram informados\n\n *Usuário", "Falha no Login",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (txtSenha.Text == "")
            {
                MessageBox.Show("Um ou mais campos obrigatórios não foram informados\n\n *Senha", "Falha no Login",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            else
            {
                DirectoryEntry    lebiscuit = new DirectoryEntry("LDAP://" + nomedoDominio);
                DirectorySearcher busca     = new DirectorySearcher(lebiscuit, "(&(objectClass=user)(objectCategory=person))");
                //busca.PropertiesToLoad.Add("department");
                busca.PropertiesToLoad.Add("cn");
                busca.PropertiesToLoad.Add("sAMAccountName");
                busca.PropertiesToLoad.Add("mail");
                busca.Sort.PropertyName = "sAMAccountName";
                busca.Filter            = "(&(objectCategory=user)(objectClass=person)(samaccountname=" + txtUsuario.Text + "))";;
                foreach (SearchResult oRes in busca.FindAll())
                {
                    nome = oRes.Properties["cn"][0].ToString();
                    //departamento = oRes.Properties["department"][0].ToString();
                }

                pai.nome          = nome;
                pai.usuarioLogado = txtUsuario.Text;
                pai.hostName      = hostName;
                //MessageBox.Show(departamento);

                //if (departamento.Contains("TI_PROJETOS"))
                //{

                using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, nomedoDominio))
                {
                    try
                    {
                        isValid = pc.ValidateCredentials(txtUsuario.Text, txtSenha.Text);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                    if (isValid == true)
                    {
                        timer1.Interval = 1000;
                        timer1.Start();
                        //groupBox1.Visible = false;
                        //label3.Visible = false;
                        //label4.Visible = false;
                        //lblBemVindoNome.Text = "Bem-Vindo " + nome.Substring(0,30);
                        //lblBemVindoNome.Visible = true;
                    }
                    if (isValid == false)
                    {
                        MessageBox.Show("Não foi possível acessar o sistema.\nVerifique suas credenciais e tente novamente",
                                        "Credenciais inválidas", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtSenha.Text = "";
                    }
                }
                //}
                //else
                //{
                //    MessageBox.Show("Somente usuários da área de TI podem utilizar este programa.", "Acesso não permitido", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //    Application.Exit();
                //}
            }

            OracleConnection conn2  = new OracleConnection("Data Source=" + localBanco + "/INTEGRACAOSP;User Id=pdvuser;Password=pdv1234;Integrated Security=no");
            OracleCommand    oCmd2  = new OracleCommand();
            string           query2 = "INSERT INTO TLOG_VALIDADOR (TLOG_DATA, TLOG_USUARIO, TLOG_HOST, TLOG_OBS) VALUES (:DATAHORA, :USUARIO, :HOST, :OBS)";

            oCmd2.CommandText = query2;
            oCmd2.CommandType = CommandType.Text;
            oCmd2.Parameters.AddWithValue("DATAHORA", DateTime.Now);
            oCmd2.Parameters.AddWithValue("USUARIO", txtUsuario.Text);
            oCmd2.Parameters.AddWithValue("HOST", hostName);
            oCmd2.Parameters.AddWithValue("OBS", "Usuário logado!");
            oCmd2.Connection = conn2;
            conn2.Open();
            OracleDataReader ler2 = oCmd2.ExecuteReader();

            conn2.Close();

            //Gravando o usuário logado na variável publica da classe do formulário pai que será acessado pelos outros formulários
            //para gravar no log.

            //FormPai pai = new FormPai();
        }
Ejemplo n.º 17
0
        public static void Kerberoast(string spn = "", string userName = "", string OUName = "", System.Net.NetworkCredential cred = null)
        {
            Console.WriteLine("[*] Action: Kerberoasting");

            if (!String.IsNullOrEmpty(spn))
            {
                Console.WriteLine("\r\n[*] ServicePrincipalName   : {0}", spn);
                GetDomainSPNTicket(spn);
            }
            else
            {
                DirectoryEntry    directoryObject = null;
                DirectorySearcher userSearcher    = null;
                string            bindPath        = "";

                try
                {
                    if (cred != null)
                    {
                        if (!String.IsNullOrEmpty(OUName))
                        {
                            string ouPath = OUName.Replace("ldap", "LDAP").Replace("LDAP://", "");
                            bindPath = String.Format("LDAP://{0}/{1}", cred.Domain, ouPath);
                        }
                        else
                        {
                            bindPath = String.Format("LDAP://{0}", cred.Domain);
                        }
                    }
                    else if (!String.IsNullOrEmpty(OUName))
                    {
                        string ouPath = OUName.Replace("ldap", "LDAP").Replace("LDAP://", "");
                        bindPath = String.Format("LDAP://{0}", ouPath);
                    }

                    if (!String.IsNullOrEmpty(bindPath))
                    {
                        directoryObject = new DirectoryEntry(bindPath);
                    }
                    else
                    {
                        directoryObject = new DirectoryEntry();
                    }

                    if (cred != null)
                    {
                        // if we're using alternate credentials for the connection
                        string userDomain = String.Format("{0}\\{1}", cred.Domain, cred.UserName);
                        directoryObject.Username = userDomain;
                        directoryObject.Password = cred.Password;

                        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, cred.Domain))
                        {
                            if (!pc.ValidateCredentials(cred.UserName, cred.Password))
                            {
                                Console.WriteLine("\r\n[X] Credentials supplied for '{0}' are invalid!", userDomain);
                                return;
                            }
                        }
                    }

                    userSearcher = new DirectorySearcher(directoryObject);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\r\n[X] Error creating the domain searcher: {0}", ex.InnerException.Message);
                    return;
                }

                // check to ensure that the bind worked correctly
                try
                {
                    Guid guid = directoryObject.Guid;
                }
                catch (DirectoryServicesCOMException ex)
                {
                    if (!String.IsNullOrEmpty(OUName))
                    {
                        Console.WriteLine("\r\n[X] Error creating the domain searcher for bind path \"{0}\" : {1}", OUName, ex.Message);
                    }
                    else
                    {
                        Console.WriteLine("\r\n[X] Error creating the domain searcher: {0}", ex.Message);
                    }
                    return;
                }

                try
                {
                    if (String.IsNullOrEmpty(userName))
                    {
                        userSearcher.Filter = "(&(samAccountType=805306368)(servicePrincipalName=*)(!samAccountName=krbtgt))";
                    }
                    else
                    {
                        userSearcher.Filter = String.Format("(&(samAccountType=805306368)(servicePrincipalName=*)(samAccountName={0}))", userName);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\r\n[X] Error settings the domain searcher filter: {0}", ex.InnerException.Message);
                    return;
                }

                try
                {
                    SearchResultCollection users = userSearcher.FindAll();

                    foreach (SearchResult user in users)
                    {
                        string samAccountName       = user.Properties["samAccountName"][0].ToString();
                        string distinguishedName    = user.Properties["distinguishedName"][0].ToString();
                        string servicePrincipalName = user.Properties["servicePrincipalName"][0].ToString();
                        Console.WriteLine("\r\n[*] SamAccountName         : {0}", samAccountName);
                        Console.WriteLine("[*] DistinguishedName      : {0}", distinguishedName);
                        Console.WriteLine("[*] ServicePrincipalName   : {0}", servicePrincipalName);
                        GetDomainSPNTicket(servicePrincipalName, userName, distinguishedName, cred);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\r\n  [X] Error executing the domain searcher: {0}", ex.InnerException.Message);
                    return;
                }
            }
            //else - search for user/OU/etc.
        }
Ejemplo n.º 18
0
        public ActionResult Index(CreateUser model)
        {
            // NetBIOS name of domain.
            var domainName = "localhost";
            // Full distinguished name of OU to create user in. E.g. OU=Users,OU=Perth,DC=Contoso,DC=com
            var userPosition    = model.Building + " " + model.Position;
            var userOU          = "OU" + @"\" + model.Building.ToString();
            var serviceUser     = "******" + @"\" + "administrator";
            var servicePassword = "******";

            // Source: http://stackoverflow.com/a/2305871
            using (var pc = new PrincipalContext(ContextType.Domain, domainName, serviceUser, servicePassword))
            {
                using (var up = new UserPrincipal(pc))
                {
                    // Create username and display name from firstname and lastname ex. lastname_f
                    var userName    = (model.LastName + "_" + (model.FirstName).Remove(1)).ToLower();
                    var displayName = model.FirstName + " " + model.LastName;
                    // Temp password setup
                    var password = "******" + model.SSN.ToString();

                    // Set the values for new user account
                    up.Name              = displayName;
                    up.DisplayName       = displayName;
                    up.GivenName         = model.FirstName;
                    up.Surname           = model.LastName;
                    up.SamAccountName    = userName;
                    up.UserPrincipalName = userName + "@ADDOMAINNAME.NET";
                    up.EmailAddress      = userName + "@webdomainname.org";
                    up.SetPassword(password);
                    up.Enabled     = true;
                    up.Description = userPosition;
                    up.ExpirePasswordNow();
                    //DirectoryEntry user = new DirectoryEntry();
                    //user.MoveTo(userOU)
                    //using (GroupPrincipal group = GroupPrincipal.FindByIdentity(up.Context, IdentityType.Name, model.Building.ToString()))                        up.IsMemberOf();

                    //using (UserPrincipal user = UserPrincipal.FindByIdentity(up.Context, IdentityType.Name, userName))
                    try
                    {
                        // Attempt to save the account to AD
                        //group.Members.Add(user);
                        up.Save();
                        ViewBag.Message = "User" + model.Name + " 's account is created";
                        ModelState.Clear();
                    }
                    catch (Exception e)
                    {
                        // Display exception(s) within validation summary
                        ModelState.AddModelError("", "Exception creating user object. " + "This user name already exist in the domain" + e);
                        return(View(model));
                    }

                    // Add the building to the newly created AD user
                    // Get the directory entry object for the user
                    //DirectoryEntry de = up.GetUnderlyingObject() as DirectoryEntry;
                    //// Set the department property to the value entered by the user
                    //de.Properties["Building"].Value = model.Building;
                    //try
                    //{
                    //    // Try to commit changes
                    //    de.CommitChanges();
                    //}
                    //catch (Exception e)
                    //{
                    //    // Display exception(s) within validation summary
                    //    ModelState.AddModelError("", "Exception adding building. " + e);

                    //    return View(model);
                    //}
                }
            }

            // Redirect to completed page if successful
            return(RedirectToAction("Completed"));
        }
 public ContactPrincipal(PrincipalContext context)
     : base(context)
 {
 }
Ejemplo n.º 20
0
    /// <summary>
    /// Validates the username and password of a given user
    /// </summary>
    /// <param name="sUserName">The username to validate</param>
    /// <param name="sPassword">The password of the username to validate</param>
    /// <returns>Returns True of user is valid</returns>
    public bool ValidateCredentials(string sUserName, string sPassword)
    {
        PrincipalContext oPrincipalContext = GetPrincipalContext();

        return(oPrincipalContext.ValidateCredentials(sUserName, sPassword));
    }
Ejemplo n.º 21
0
        /// <summary>
        /// The get user.
        /// </summary>
        public static UserPrincipal GetUser(string identity, IdentityType identityType)
        {
            PrincipalContext principalContext = GetPrincipalContext;

            return(UserPrincipal.FindByIdentity(principalContext, identityType, identity));
        }
Ejemplo n.º 22
0
        public static void GetAllUsersFromAD()
        {
            using (var context = new PrincipalContext(ContextType.Domain, "xyzDomain"))
            {
                using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                {
                    foreach (var result in searcher.FindAll())
                    {
                        DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                        if (de.Properties["info"].Value != null)
                        {
                            //Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
                            //Console.WriteLine("Last Name : " +  de.Properties["sn"].Value);
                            //Console.WriteLine("Location : " +   de.Properties["l"].Value);
                            //Console.WriteLine("title : " +      de.Properties["title"].Value);
                            //Console.WriteLine("postalCode : " + de.Properties["postalCode"].Value);
                            //Console.WriteLine("telephoneNumber : " + de.Properties["telephoneNumber"].Value);
                            //Console.WriteLine("whenChanged : " + de.Properties["whenChanged"].Value);
                            //Console.WriteLine("streetAddress : " + de.Properties["streetAddress"].Value);
                            //Console.WriteLine("mobile : " + de.Properties["mobile"].Value);
                            //Console.WriteLine("msExchWhenMailboxCreated : " + de.Properties["msExchWhenMailboxCreated"].Value);
                            //Console.WriteLine("msExchExtensionAttribute19 : " + de.Properties["msExchExtensionAttribute19"].Value);
                            //Console.WriteLine("SAPID : " + de.Properties["physicalDeliveryOfficeName"].Value);
                            //Console.WriteLine("Gender : " + de.Properties["info"].Value.ToString().Substring(de.Properties["info"].Value.ToString().IndexOf("Gender : ") + 9));
                            //Console.WriteLine("Seat Code : " + de.Properties["info"].Value.ToString().Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)[1].ToString().Substring("Seat Code : ".Length));
                            //Console.WriteLine("SAM account name   : " + de.Properties["samAccountName"].Value);
                            //Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
                            //Console.WriteLine();

                            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString());
                            conn.Open();
                            SqlCommand cmd = new SqlCommand("InsertActiveUser ", conn);
                            cmd.CommandType = System.Data.CommandType.StoredProcedure;

                            cmd.Parameters.AddWithValue("@FirstName", de.Properties["givenName"].Value);
                            cmd.Parameters.AddWithValue("@LastName", de.Properties["sn"].Value);
                            cmd.Parameters.AddWithValue("@Location", de.Properties["l"].Value);
                            cmd.Parameters.AddWithValue("@Title", de.Properties["title"].Value);
                            cmd.Parameters.AddWithValue("@postalCode", de.Properties["postalCode"].Value);
                            cmd.Parameters.AddWithValue("@telephoneNumber", de.Properties["telephoneNumber"].Value);
                            cmd.Parameters.AddWithValue("@whenChanged", de.Properties["whenChanged"].Value);
                            cmd.Parameters.AddWithValue("@streetAddress", de.Properties["streetAddress"].Value);
                            cmd.Parameters.AddWithValue("@mobile", de.Properties["mobile"].Value);
                            cmd.Parameters.AddWithValue("@msExchWhenMailboxCreated", de.Properties["msExchWhenMailboxCreated"].Value);
                            cmd.Parameters.AddWithValue("@msExchExtensionAttribute19", de.Properties["msExchExtensionAttribute19"].Value);
                            cmd.Parameters.AddWithValue("@SAPID", de.Properties["physicalDeliveryOfficeName"].Value);
                            try
                            {
                                cmd.Parameters.AddWithValue("@Gender", de.Properties["info"].Value.ToString().Substring(de.Properties["info"].Value.ToString().IndexOf("Gender : ") + 9));

                                cmd.Parameters.AddWithValue("@SeatCode", de.Properties["info"].Value.ToString().Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)[1].ToString().Substring("Seat Code : ".Length));
                            }
                            catch { }
                            cmd.Parameters.AddWithValue("@SAMAccountName", de.Properties["samAccountName"].Value);
                            cmd.Parameters.AddWithValue("@UserPrincipalName", de.Properties["userPrincipalName"].Value);

                            cmd.ExecuteNonQuery();
                            conn.Close();
                        }
                    }
                }
            }
            Console.ReadLine();
        }
Ejemplo n.º 23
0
        /// <summary>
        /// The get group.
        /// </summary>
        public static GroupPrincipal GetGroup(PrincipalContext pContext)
        {
            var groupByGroupPrincipal = new GroupPrincipal(pContext, "*");

            return(groupByGroupPrincipal);
        }
Ejemplo n.º 24
0
        //public bool ValidateLoginCredentials(DynamicSearchResult Result)
        //{
        //    bool loginFlag = false;
        //    string[] UserCredentials = Result.columnValues.Split(',');
        //    string Id = UserCredentials[0].ToString();
        //    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

        //    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, UserCredentials[0].Trim());
        //    if (user != null)
        //    {
        //        if (ctx.ValidateCredentials(UserCredentials[0], UserCredentials[1]))
        //        {
        //            loginFlag = true;
        //        }
        //    }
        //    else if (user == null)
        //    {
        //        string empNo = DB.Employees.Where(li => li.DomainId == Id).Select(li => li.EmployeeNo).SingleOrDefault();
        //        if (empNo != "")
        //        {
        //            loginFlag = true;
        //        }
        //    }
        //    return loginFlag;
        //}


        public EmployeeModel ValidateLoginCredentials(DynamicSearchResult Result)
        {
            //var session = HttpContext.Current.Session;
            DB.Configuration.ProxyCreationEnabled = false;
            EmployeeModel employee = new EmployeeModel();

            string[]         UserCredentials = Result.columnValues.Split(',');
            string           Id  = UserCredentials[0].ToString();
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

            UserPrincipal user = UserPrincipal.FindByIdentity(ctx, UserCredentials[0].Trim());

            if (user != null)
            {
                if (ctx.ValidateCredentials(UserCredentials[0], UserCredentials[1]))
                {
                    var data = DB.Employees.Where(li => li.DomainId == Id).FirstOrDefault();
                    if (data != null)
                    {
                        employee.EmployeeNo      = data.EmployeeNo;
                        employee.Name            = data.Name;
                        employee.EMail           = data.EMail;
                        employee.OrgDepartmentId = data.OrgDepartmentId;
                        if (data.OrgDepartmentId != null)
                        {
                            employee.OrgDepartmentName = DB.OrgDepartments.Where(li => li.OrgDepartmentId == data.OrgDepartmentId).FirstOrDefault().OrgDepartment1;
                        }
                        employee.DOL    = data.DOL;
                        employee.RoleId = data.RoleId;
                    }
                }
            }
            else if (user == null)
            {
                var data = DB.Employees.Where(li => li.DomainId == Id).FirstOrDefault();
                if (data != null)
                {
                    employee.EmployeeNo      = data.EmployeeNo;
                    employee.Name            = data.Name;
                    employee.EMail           = data.EMail;
                    employee.OrgDepartmentId = data.OrgDepartmentId;
                    if (data.OrgDepartmentId != null)
                    {
                        employee.OrgDepartmentName = DB.OrgDepartments.Where(li => li.OrgDepartmentId == data.OrgDepartmentId).FirstOrDefault().OrgDepartment1;
                    }
                    employee.DOL    = data.DOL;
                    employee.RoleId = data.RoleId;
                }
                //else
                //{
                //    InValidUser();
                //}
            }
            //if (session != null)
            //{
            //    session["name"] = employee.Name;
            //    session["id"] = employee.EmployeeNo.ToString();
            //    string SessionID = session.SessionID;
            //}
            return(employee);
        }
Ejemplo n.º 25
0
 private static UserPrincipal AcquireUserPricipal(PrincipalContext context, string username)
 {
     return(UserPrincipal.FindByIdentity(context, username));
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Optionally called during [list construction](@ref AcUtils#AcUsers#AcUsers) to initialize the
        /// <a href="class_ac_utils_1_1_ac_user.html#properties">default set</a> of regular user properties
        /// and others from Active Directory. This method is called internally and not by user code.
        /// </summary>
        /// <param name="dc">List of DomainElement objects as defined in <tt>\<prog_name\>.exe.config</tt> \e domains section. Used to initialize
        /// the user properties <a href="class_ac_utils_1_1_ac_user.html#properties">default set</a> from Active Directory.</param>
        /// <param name="pc">List of PropElement objects as defined in <tt>\<prog_name\>.exe.config</tt> \e properties section. Used to add
        /// and initialize user properties from Active Directory that are outside the regular <a href="class_ac_utils_1_1_ac_user.html#properties">default set</a>.</param>
        /// <returns>\e true if no exception was thrown and operation succeeded, \e false otherwise.</returns>
        /// <exception cref="Exception">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on failure to handle a range of exceptions.</exception>
        /*! \sa DomainCollection, PropCollection, Other */
        /*! \attention User properties require that AccuRev principal names match login names stored on the LDAP server. */
        internal async Task <bool> initFromADAsync(DomainCollection dc, PropCollection pc = null)
        {
            return(await Task.Run(() =>
            {
                bool ret = true; // assume success
                foreach (DomainElement de in dc)
                {
                    PrincipalContext ad = null;
                    try
                    {
                        ad = new PrincipalContext(ContextType.Domain, de.Host.Trim(), de.Path.Trim());
                        UserPrincipal up = new UserPrincipal(ad);
                        up.SamAccountName = Principal.Name;
                        using (PrincipalSearcher ps = new PrincipalSearcher(up))
                        {
                            UserPrincipal rs = (UserPrincipal)ps.FindOne();
                            if (rs != null)
                            {
                                _givenName = rs.GivenName;
                                _middleName = rs.MiddleName;
                                _surname = rs.Surname;
                                _displayName = rs.DisplayName;
                                _business = rs.VoiceTelephoneNumber;
                                _emailAddress = rs.EmailAddress;
                                _description = rs.Description;
                                _distinguishedName = rs.DistinguishedName;

                                if (pc != null)
                                {
                                    DirectoryEntry lowerLdap = (DirectoryEntry)rs.GetUnderlyingObject();
                                    foreach (PropElement pe in pc)
                                    {
                                        PropertyValueCollection pvc = lowerLdap.Properties[pe.Field];
                                        if (pvc != null)
                                        {
                                            _other.Add(pe.Title.Trim(), pvc.Value);
                                        }
                                    }
                                }

                                break;
                            }
                        }
                    }

                    catch (Exception ecx)
                    {
                        ret = false;
                        AcDebug.Log($"Exception caught and logged in AcUser.initFromADAsync{Environment.NewLine}{ecx.Message}");
                    }

                    // avoid CA2202: Do not dispose objects multiple times
                    finally { if (ad != null)
                              {
                                  ad.Dispose();
                              }
                    }
                }

                return ret;
            }).ConfigureAwait(false));
        }
Ejemplo n.º 27
0
        public List <Dictionary <string, object> > validateUser(HttpRequestMessage req)
        {
            var    postedString  = req.Content.ReadAsStringAsync().Result;
            string base64Encoded = postedString;
            string base64Decoded;

            byte[] data = System.Convert.FromBase64String(base64Encoded);
            base64Decoded = System.Text.ASCIIEncoding.ASCII.GetString(data);
            dynamic d = JObject.Parse(Convert.ToString(base64Decoded));

            string username = Convert.ToString(d.username);
            string pwd      = Convert.ToString(d.password);
            List <Dictionary <string, object> > rows = new List <Dictionary <string, object> >();
            Dictionary <string, object>         row;

            row = new Dictionary <string, object>();
            obj = new DSL();
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "IEA"))
            {
                bool isValid = pc.ValidateCredentials(username, pwd, ContextOptions.Negotiate);
                if (isValid)
                {
                    using (UserPrincipal user = UserPrincipal.FindByIdentity(pc, username))
                    {
                        if (user != null)
                        {
                            //string employeeID = user.EmployeeId;
                            int get_session_id = obj.getSessionID(user.SamAccountName);
                            if (get_session_id > 0)
                            {
                                string Name = user.DisplayName;
                                row.Add("UserName", username);
                                row.Add("Name", Name);
                                row.Add("UserValidated", "true");
                                row.Add("UserID", user.SamAccountName);
                                row.Add("SessionID", get_session_id);
                                rows.Add(row);
                            }
                            else
                            {
                                string Name = user.DisplayName;
                                row.Add("UserName", username);
                                row.Add("Name", Name);
                                row.Add("UserValidated", "true");
                                row.Add("UserID", user.SamAccountName);
                                row.Add("SessionID", -1);
                                rows.Add(row);
                            }
                            return(rows);
                        }
                        else
                        {
                            row.Add("UserName", username);
                            row.Add("Name", "Not Found");
                            row.Add("UserValidated", "true");
                            row.Add("SessionID", -1);
                            rows.Add(row);
                            //string employeeID = user.EmployeeId;
                            return(rows);
                        }
                    }
                }
                else
                {
                    row.Add("UserName", username);
                    row.Add("Name", "Not Found");
                    row.Add("UserValidated", "false");
                    rows.Add(row);
                    //string employeeID = user.EmployeeId;
                    return(rows);
                }
            }
        }
Ejemplo n.º 28
0
 public System.Windows.Controls.UserControl PlControl(string login, string pass, string pathToConfig, DirectoryEntry entry, PrincipalContext context)
 {
     return(new ControlPlMain(this, login, pass, pathToConfig, entry, context));
 }
Ejemplo n.º 29
0
 // Implement the overloaded search method FindByIdentity.
 public static new UserPrincipalEx FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
 {
     return((UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityType, identityValue));
 }
 public UserPrincipalFull(PrincipalContext context)
     : base(context)
 {
 }
Ejemplo n.º 31
0
        private void bgLDAP_DoWork(object sender, DoWorkEventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
            var    appSettings   = ConfigurationManager.AppSettings;
            string checkreplace  = ConfigurationManager.AppSettings["checkreplace"];
            string defaultdomain = "";
            string replacedomain = "";

            txtFile.Text = @"ldapusers.txt";
            int usercounter = 0;

            if (checkreplace == "yes")
            {
                defaultdomain = ConfigurationManager.AppSettings["defaultdomain"];
                replacedomain = ConfigurationManager.AppSettings["replacedomain"];
            }
            txtLog.Text += "Discovering users... Please wait." + Environment.NewLine;

            string directorylisttxt = @"ldapusers.txt";

            if (File.Exists(directorylisttxt))
            {
                File.Delete(directorylisttxt);
            }

            StreamWriter userstxt = new StreamWriter(directorylisttxt);
            string       domain   = txtDomain.Text;

            using (var context = new PrincipalContext(ContextType.Domain, domain))
            {
                using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                {
                    foreach (var result in searcher.FindAll())
                    {
                        if (bgLDAP.CancellationPending)
                        {
                            e.Cancel        = true;
                            stripLabel.Text = "Operation was canceled!";
                            break;
                        }

                        usercounter++;
                        stripLabel.Text = (usercounter + " users found.");
                        System.DirectoryServices.DirectoryEntry de = result.GetUnderlyingObject() as System.DirectoryServices.DirectoryEntry;
                        string replace_email = (string)(de.Properties["userPrincipalName"].Value);
                        // Did the user have a valid entry?
                        if (replace_email != null)
                        {
                            if (checkreplace == "yes")
                            {
                                replace_email = replace_email.Replace(defaultdomain, replacedomain);
                                userstxt.WriteLine(replace_email);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Invalid user information. Proceeding to next entry.");
                        }
                    }
                    userstxt.Dispose();
                }
            }
        }
 // Implement the overloaded search method FindByIdentity.
 public static new ComputerPrincipalFull FindByIdentity(PrincipalContext context,
     IdentityType identityType,
     string identityValue)
 {
     return (ComputerPrincipalFull) FindByIdentityWithType(context,
         typeof (ComputerPrincipalFull),
         identityType,
         identityValue);
 }
        public static PrincipalContext GetPrincipalContext()
        {
            PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine);

            return(oPrincipalContext);
        }
Ejemplo n.º 34
0
 public SavoniaUserPrincipal(PrincipalContext context) : base(context)
 {
 }
 public ComputerPrincipalFull(PrincipalContext context, string samAccountName, string password, bool enabled)
     : base(context, samAccountName, password, enabled)
 {
 }
Ejemplo n.º 36
0
        public void CreateConcreteQueryFilter_ShouldOnlyTransferSetQueryFiltersToTheConcreteQueryFilter()
        {
            var             accountExpirationDateFilter          = DateTime.Now;
            const MatchType accountExpirationDateFilterMatchType = MatchType.LessThan;
            const string    descriptionFilter   = "Test";
            const bool      enabledFilter       = true;
            const string    homeDirectoryFilter = "Test";

            using (ShimsContext.Create())
            {
                bool advancedSearchFilterAccountExpirationDateIsCalled = false;
                bool advancedSearchFilterAccountLockoutTimeIsCalled    = false;
                bool descriptionSetIsCalled   = false;
                bool enabledSetIsCalled       = false;
                bool homeDirectorySetIsCalled = false;
                bool homeDriveSetIsCalled     = false;
                bool nameSetIsCalled          = false;

                ShimAdvancedFilters.AllInstances.AccountExpirationDateDateTimeMatchType = delegate(AdvancedFilters advancedFilters, DateTime dateTime, MatchType matchType)
                {
                    if (dateTime == accountExpirationDateFilter && matchType == accountExpirationDateFilterMatchType)
                    {
                        advancedSearchFilterAccountExpirationDateIsCalled = true;
                    }
                };

                ShimAdvancedFilters.AllInstances.AccountLockoutTimeDateTimeMatchType = delegate { advancedSearchFilterAccountLockoutTimeIsCalled = true; };

                ShimPrincipal.AllInstances.DescriptionSetString = delegate(Principal principal, string description)
                {
                    if (description == descriptionFilter)
                    {
                        descriptionSetIsCalled = true;
                    }
                };

                ShimPrincipal.AllInstances.NameSetString = delegate { nameSetIsCalled = true; };

                ShimAuthenticablePrincipal.AllInstances.EnabledSetNullableOfBoolean = delegate(AuthenticablePrincipal authenticablePrincipal, bool?enabled)
                {
                    if (enabled == true)
                    {
                        enabledSetIsCalled = true;
                    }
                };

                ShimAuthenticablePrincipal.AllInstances.HomeDirectorySetString = delegate(AuthenticablePrincipal authenticablePrincipal, string homeDirectory)
                {
                    if (homeDirectory == homeDirectoryFilter)
                    {
                        homeDirectorySetIsCalled = true;
                    }
                };

                ShimAuthenticablePrincipal.AllInstances.HomeDriveSetString = delegate { homeDriveSetIsCalled = true; };

                using (var authenticablePrincipalQueryFilter = new AuthenticablePrincipalQueryFilter())
                {
                    authenticablePrincipalQueryFilter.AdvancedSearchFilter.AccountExpirationDate(accountExpirationDateFilter, accountExpirationDateFilterMatchType);
                    authenticablePrincipalQueryFilter.Description   = descriptionFilter;
                    authenticablePrincipalQueryFilter.Enabled       = enabledFilter;
                    authenticablePrincipalQueryFilter.HomeDirectory = homeDirectoryFilter;

                    using (var concretePrincipalContext = new PrincipalContext(ContextType.Machine))
                    {
                        using (var principalContext = (PrincipalContextWrapper)concretePrincipalContext)
                        {
                            Assert.IsFalse(advancedSearchFilterAccountExpirationDateIsCalled);
                            Assert.IsFalse(advancedSearchFilterAccountLockoutTimeIsCalled);
                            Assert.IsFalse(descriptionSetIsCalled);
                            Assert.IsFalse(enabledSetIsCalled);
                            Assert.IsFalse(homeDirectorySetIsCalled);
                            Assert.IsFalse(homeDriveSetIsCalled);
                            Assert.IsFalse(nameSetIsCalled);

                            authenticablePrincipalQueryFilter.CreateConcreteQueryFilter(principalContext);

                            Assert.IsTrue(advancedSearchFilterAccountExpirationDateIsCalled);
                            Assert.IsFalse(advancedSearchFilterAccountLockoutTimeIsCalled);
                            Assert.IsTrue(descriptionSetIsCalled);
                            Assert.IsTrue(enabledSetIsCalled);
                            Assert.IsTrue(homeDirectorySetIsCalled);
                            Assert.IsFalse(homeDriveSetIsCalled);
                            Assert.IsFalse(nameSetIsCalled);
                        }
                    }
                }
            }
        }
 public ComputerPrincipalFull(PrincipalContext context)
     : base(context)
 {
 }
Ejemplo n.º 38
0
        /// <summary>
        /// Возвращает данные пользователя из AD
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public static Models.AuthUser GetUserFromAD(string login)
        {
            Models.AuthUser user           = new Models.AuthUser();
            string          domainNetBIOS  = login.Split('\\')[0];
            string          samAccountName = login.Split('\\')[1];
            string          controller     = "";
            string          username       = "";
            string          password       = "";
            string          domain         = "";
            string          ldap           = "";

            try {
                switch (domainNetBIOS)
                {
                case "UKRTRANSNAFTA":
                    controller = System.Configuration.ConfigurationManager.AppSettings["kyivDC"];
                    username   = "******";
                    password   = "";
                    domain     = "ukrtransnafta.com";
                    ldap       = "DC=ukrtransnafta,DC=com";
                    break;

                case "ODESSA":
                    controller = System.Configuration.ConfigurationManager.AppSettings["odessaDC"];
                    username   = "******";
                    password   = "";
                    domain     = "odessa.ukrtransnafta.com";
                    ldap       = "DC=odessa,DC=ukrtransnafta,DC=com";
                    break;

                case "KREMEN":
                    controller = System.Configuration.ConfigurationManager.AppSettings["kremenDC"];
                    username   = "******";
                    password   = "";
                    domain     = "kremen.ukrtransnafta.com";
                    ldap       = "DC=kremen,DC=ukrtransnafta,DC=com";
                    break;

                case "DRUZHBA_AD":
                    controller = System.Configuration.ConfigurationManager.AppSettings["lvivDC"];
                    username   = "******";
                    password   = "";
                    domain     = "druzhba.ukrtransnafta.com";
                    ldap       = "DC=druzhba,DC=ukrtransnafta,DC=com";
                    break;

                case "DRUZHBA":
                    controller = System.Configuration.ConfigurationManager.AppSettings["lvivDCOLD"];
                    domain     = "druzhba.lviv.ua";
                    ldap       = "DC=druzhba,DC=lviv,DC=ua";

                    var ldapPort = 389;
                    var pageSize = 1000;

                    var openLDAPHelper = new LDAPHelper(
                        ldap,
                        controller,
                        ldapPort,
                        AuthType.Basic,
                        pageSize);

                    var searchFilter       = "uid=" + samAccountName;
                    var attributesToLoad   = new[] { "mail", "cn", "displayName" };
                    var pagedSearchResults = openLDAPHelper.PagedSearch(
                        searchFilter,
                        attributesToLoad);

                    foreach (var searchResultEntryCollection in pagedSearchResults)
                    {
                        foreach (SearchResultEntry searchResultEntry in searchResultEntryCollection)
                        {
                            if (searchResultEntry.Attributes.Count > 0)
                            {
                                user.email = searchResultEntry.Attributes["mail"][0].ToString();
                                user.FIO   = searchResultEntry.Attributes["displayName"][0].ToString();
                            }
                        }
                    }
                    break;
                }

                if (domainNetBIOS != "DRUZHBA")
                {
                    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, controller);
                    UserPrincipal    u   = UserPrincipal.FindByIdentity(ctx, samAccountName);
                    if (u != null)
                    {
                        user.email = u.EmailAddress;
                        user.FIO   = u.DisplayName;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(user);
        }