当前位置: 首页>>代码示例>>C#>>正文


C# AccountManagement.PrincipalContext类代码示例

本文整理汇总了C#中System.DirectoryServices.AccountManagement.PrincipalContext的典型用法代码示例。如果您正苦于以下问题:C# PrincipalContext类的具体用法?C# PrincipalContext怎么用?C# PrincipalContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


PrincipalContext类属于System.DirectoryServices.AccountManagement命名空间,在下文中一共展示了PrincipalContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: UserInGroup

        public static bool UserInGroup(IPrincipal user, params AdGroup[] groups)
        {
            using (WindowsImpersonationContextFacade impersonationContext
                = new WindowsImpersonationContextFacade(
                    nc))
            {
                var context = new PrincipalContext(ContextType.Domain);
                var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName,
                    user.Identity.Name);

                if (userPrincipal.IsMemberOf(context, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(AdGroup.SuperAdmin)))
                {
                    return true;
                } //Если юзер Суперадмин
                if (userPrincipal.IsMemberOf(context, IdentityType.Sid,
                    AdUserGroup.GetSidByAdGroup(AdGroup.SpeCalcKontroler)))
                {
                    return true;
                } //Если юзер Контролер

                foreach (var grp in groups)
                {
                    if (userPrincipal.IsMemberOf(context, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(grp)))
                    {
                        return true;
                    }
                }

                return false;
            }
        }
开发者ID:aleks19921015,项目名称:TenderProcessing,代码行数:31,代码来源:AdHelper.cs

示例2: treeViewGroup_AfterSelect

        private void treeViewGroup_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                //Start of: Change Font of  selected node
                if (prevNode != null)
                {
                    prevNode.ForeColor = Color.Black;
                    prevNode.NodeFont = new Font(Font.FontFamily, Font.Size, FontStyle.Regular);
                }

                prevNode = treeViewGroup.SelectedNode;

                treeViewGroup.SelectedNode.ForeColor = Color.Blue;
                treeViewGroup.SelectedNode.NodeFont = new Font(Font.FontFamily.Name, Font.Size, FontStyle.Regular);
                //End of: Change Font of  selected node

                PrincipalContext ctx = new PrincipalContext(ContextType.Domain, treeViewGroup.SelectedNode.ImageKey); 
                
                GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, treeViewGroup.SelectedNode.Text);


                userDetails = (from u in grp.Members
                               select new UserDetails { DisplayName = u.DisplayName, UserName = u.SamAccountName,Domain = u.Context.Name }).OrderBy(x => x.DisplayName).ToList();
             
                userControlListing.DataSource = userDetails;
                
            }
            catch (Exception)
            {
                throw;
            }
        }
开发者ID:m12k,项目名称:Files,代码行数:33,代码来源:FormActiveDirectoryUsersList.cs

示例3: AuthorizeCore

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (base.AuthorizeCore(httpContext))
            {
                /* Return true immediately if the authorization is not 
                locked down to any particular AD group */
                if (String.IsNullOrEmpty(Groups))
                { 
                    return true;
                }
                
                string DomainName = ConfigurationManager.AppSettings["Domain"].ToString();
                if (string.IsNullOrEmpty(DomainName))
                {
                    throw new ArgumentException("Domain missing from AppSettings!");
                }
                    // Get the AD groups
                    var groups = Groups.Split(',').ToList();

                // Verify that the user is in the given AD group (if any)
                var context = new PrincipalContext(ContextType.Domain,DomainName);

                var userPrincipal = UserPrincipal.FindByIdentity(context,IdentityType.SamAccountName,httpContext.User.Identity.Name);

                foreach (var group in groups)
                {
                    if (userPrincipal.IsMemberOf(context, IdentityType.Name, group))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
开发者ID:chuckfrazier,项目名称:DataPlatform,代码行数:34,代码来源:AuthorizeADAttribute.cs

示例4: button1_Click

		private void button1_Click(object sender, EventArgs e)
		{
			if (this.txtUserName.Text.Length < 1)
			{
				MessageBox.Show("Please Enter User Name");
				return;
			}
			if (this.txtPassword.Text.Length < 1)
			{
				MessageBox.Show("Please Enter Password");
				return;
			}
			PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "COS");
			principalContext.ValidateCredentials(this.txtUserName.Text, this.txtPassword.Text);
			try
			{
				if (!principalContext.ValidateCredentials(this.txtUserName.Text, this.txtPassword.Text))
				{
					this.txtPassword.Text = string.Empty;
					MessageBox.Show("User Name or Password Not correct");
				}
				else
				{
					(new frmMain()).Show();
					base.Hide();
				}
			}
			catch (Exception exception)
			{
				MessageBox.Show(exception.ToString());
			}
		}
开发者ID:connecticutortho,项目名称:ct-ortho-repositories4,代码行数:32,代码来源:Login.cs

示例5: _LoggedInAs

        public ActionResult _LoggedInAs()
        {
            User user = new User();

            try
            {
                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                WindowsPrincipal principal = (WindowsPrincipal) Thread.CurrentPrincipal;
                //String adDomainUserName = principal.Identity.Name;

                using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
                {
                    UserPrincipal up = UserPrincipal.FindByIdentity(pc, principal.Identity.Name);
                    user.FirstName = up.GivenName;
                    user.LastName = up.Surname;
                    user.Email = up.EmailAddress;
                    user.UserName = (principal.Identity.Name).Split('\\')[1];
                }

               /* if (adDomainUserName != null)
                {
                    string adUserName = adDomainUserName.Split('\\')[1];

                    user = _ldapService.GetUserByUserName(adUserName);
                }*/
            }
            catch (Exception e)
            {
                logger.Error("Exception", e);
            }

            Session["user"] = user;

            return View(user);
        }
开发者ID:patrickwensel,项目名称:WS,代码行数:35,代码来源:SharedController.cs

示例6: Create

        public ActionResult Create()
        {
            var name = User.Identity.Name;
            UserPrincipal user;

            using (var pc = new PrincipalContext(ContextType.Domain, "smausa"))
            {
                user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, name);
            }

            if (user == null)
            {
                throw new Exception("Active Directory user not found!");
            }

            var player = new Player
            {
                Username = name,
                FirstName = user.GivenName,
                Surname = user.Surname,
                Email = user.EmailAddress,
                Notifications = !string.IsNullOrWhiteSpace(user.EmailAddress)
            };

            return View(player);
        }
开发者ID:ryandimick,项目名称:smartpong,代码行数:26,代码来源:PlayersController.cs

示例7: IsGroupMember

        private static bool IsGroupMember(string userName, string Group)
        {
#if DEBUG
            return true;
            //PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "reckner.com", "fmedvedik", "(manos)3k");
            //PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "10.0.0.2", "fmedvedik", "(manos)3k");
            //  PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
            //  PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "reckner.com");
#else
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "reckner.com");
            


            var findByIdentity = UserPrincipal.FindByIdentity(ctx, userName);
            bool retVal = false;
            if (findByIdentity != null)
            {
                List<string> result;
                using (var src = findByIdentity.GetGroups(ctx))
                {
                    result = new List<string>();
                    src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
                }
                var l = result.FirstOrDefault(s => s.Equals(Group));
                retVal = (l != null);
            }
            ctx.Dispose();
            return retVal;
#endif
        }
开发者ID:FrankMedvedik,项目名称:coopcheck,代码行数:30,代码来源:UserAuthSvc.cs

示例8: FindByIdentity

 // Implement the overloaded search method FindByIdentity.
 public static new ExtendedUserPrincipal FindByIdentity(PrincipalContext context,
                                                string identityValue)
 {
     return (ExtendedUserPrincipal)FindByIdentityWithType(context,
                                                  typeof(ExtendedUserPrincipal),
                                                  identityValue);
 }
开发者ID:chcosta,项目名称:corefx,代码行数:8,代码来源:ExtendedUserPrincipal.cs

示例9: Login

 public bool Login(String userName, String password)
 {
     PrincipalContext pc = new PrincipalContext(ContextType.Domain, this.domainName);
         bool isValid = false;
         isValid = pc.ValidateCredentials(userName, password);
         return isValid;
 }
开发者ID:VikySihabudin,项目名称:Landai,代码行数:7,代码来源:LDAP.cs

示例10: getMatchingStudents

        public static List<Student> getMatchingStudents(string givenName, string surname)
        {
            List<Student> matches = new List<Student>();

            using (PrincipalContext pc = new PrincipalContext(
                ContextType.ApplicationDirectory, "ailds01v.home.ad1.sou.edu:1556",
                "CN=Users,CN=University", ContextOptions.Negotiate | ContextOptions.SecureSocketLayer))
            {
                SouPerson findPerson = new SouPerson(pc);
                findPerson.GivenName = givenName;
                findPerson.Surname = surname;

                PrincipalSearcher searcher = new PrincipalSearcher(findPerson);
                PrincipalSearchResult<Principal> results = searcher.FindAll();

                foreach (SouPerson person in results)
                {
                    if (person.souStudent == true)
                    {
                        Student s = new Student();
                        s.setKey1(person.souStudentKey1);
                        s.setKey2(person.souStudentKey2);
                        s.setUsername(person.Name);
                        matches.Add(s);
                    }
                }

                return matches;
            }
        }
开发者ID:andrewkrug,项目名称:seadragon,代码行数:30,代码来源:LDS.cs

示例11: GetClientRoles

 internal static IEnumerable<BplRole> GetClientRoles(string loginName) {
    try {
       using (var context = new PrincipalContext(ContextType.Domain, ADServer, ADUserContainer, ADUsername, ADPassword)) {
          using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, loginName)) {
             try {
                var groups = user.GetAuthorizationGroups();
                var roles = groups.Select(g => BplRole.Get(g.Name)).Where(r => r != null).ToArray();
                return roles;
             } catch (PrincipalOperationException pex) {
                Log.Exception(pex, Severity.Warning, "Unable to retrive client roles on trusted domain. Fall back to untrusted.");
             }
             //TK: Fallback to untrusted communication or DNS issues. I do not believe i need to do this!
             var usr = (DirectoryEntry)user.GetUnderlyingObject();
             var dgroups = usr.Invoke("Groups");
             var droles = new List<BplRole>();
             foreach (var g in (IEnumerable)dgroups) {
                var ge = new DirectoryEntry(g);
                var role = BplRole.Get(ge.Name.RemoveAll("CN="));
                if (role != null) {
                   droles.Add(role);
                }
             }
             return droles;
          }
       }
    } catch (Exception e) {
       Log.Exception(e, "Unable to retrive client roles");
    }
    return null;
 }
开发者ID:borkaborka,项目名称:gmit,代码行数:30,代码来源:AuthServices.cs

示例12: IsUserMemberOfAccessControlGroup

        public bool IsUserMemberOfAccessControlGroup(string accessControlGroup)
        {
            if (string.IsNullOrWhiteSpace(accessControlGroup))
            {
                return true;
            }

            PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);

            GroupPrincipal groupPrincipal = GroupPrincipal
                .FindByIdentity(principalContext, accessControlGroup);

            if (groupPrincipal == null)
            {
                throw new FingertipsException("Could not find group: " + accessControlGroup);
            }

            UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, Name);
            if (userPrincipal == null)
            {
                throw new FingertipsException("Could not find user: " + Name);
            }

            return userPrincipal.IsMemberOf(groupPrincipal);
        }
开发者ID:PublicHealthEngland,项目名称:fingertips-open,代码行数:25,代码来源:UserDetails.cs

示例13: crearEstudiante2

        //BASARSE EN ESTO PARA ARREGLAR TODO LO QUE SEA CON EL AD
        //Una mejor manera de hacerlo http://johnbarquin.wordpress.com/2008/06/12/servicios-de-directorio-en-net-35/
        /// <summary>
        /// Método que se encarga de crear un usuario estudiante en Active Directory
        /// </summary>
        /// <param name="estudiante">
        /// Los datos del estudiante (en un tipo Usuario) por ingresar a Active Directory
        /// </param>
        public Boolean crearEstudiante2(Usuario estudiante)
        {
            String nombre_completo = estudiante.Carnet + " " + estudiante.Nombre + " " + estudiante.Apellidos + " " + estudiante.Carrera;
            try	{

            PrincipalContext contextoDominio = new PrincipalContext(ContextType.Domain, Constantes.DOM, Constantes.AD_USER, Constantes.AD_PASS);
            UserPrincipal usuario = new UserPrincipal(contextoDominio, estudiante.UID, estudiante.Contrasena, true);
            usuario.SamAccountName = estudiante.UID;// LEGACY: Cuenta de estudiante Pre-Win2000
            usuario.UserPrincipalName = estudiante.UID + Constantes.DOMINIO;//Debe de contener el dominio
            usuario.GivenName = estudiante.Nombre;
            usuario.Surname = estudiante.Apellidos;
            usuario.DisplayName = nombre_completo;
            usuario.Description = "Estudiante";
            usuario.HomeDirectory = getHomeDirectoryAD(estudiante);
            usuario.EmailAddress = estudiante.Correo;
            usuario.HomeDrive = "M";
            usuario.PasswordNeverExpires = true;
            usuario.Save();
            usuario.SetPassword(estudiante.Contrasena);
            usuario.Save();
            return true;
            }
            catch (Exception e)
            {
                _conexionBD = new ManejoBD();
                _conexionBD.insertarBitacoraError(e.ToString(), "");
                return false;
            }
        }
开发者ID:hrbie,项目名称:ModulosTI,代码行数:37,代码来源:ConexionAD.cs

示例14: buttonGetUsers_Click

        private void buttonGetUsers_Click(object sender, EventArgs e)
        {
            _users = loadUsersFromTxt();
             if (_users.Count == 0)
             {
            string domainName = textBoxDomain.Text;
            using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName))
            {
               GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, textBoxGroup.Text);
               if (group != null)
               {
                  HashSet<UserData> usersHash = new HashSet<UserData>();
                  IterateGroup(group, usersHash);
                  _users = usersHash.ToList();
               }
               else
               {
                  MessageBox.Show("Группа не найдена");
               }
            }
             }
             listBoxUsers.DataSource = _users.ToList();
             saveUsersToTxt(_users);

             MessageBox.Show("Готово");
        }
开发者ID:vildar82,项目名称:AD-Computers-Users,代码行数:26,代码来源:Form1.cs

示例15: SearchComp

 private static void SearchComp(List<CompData> comps, string domainName)
 {
     using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName))
      {
     foreach (var comp in comps)
     {
        if (comp.CompName == null)
        {
           var sp = new ComputerPrincipal(ctx);
           sp.Description = comp.User.Name;
           var searcher = new PrincipalSearcher(sp);
           var res = searcher.FindAll();
           foreach (var p in res)
           {
              if (p is ComputerPrincipal)
              {
                 var findComp = (ComputerPrincipal)p;
                 comp.CompName = findComp.Name;
                 comp.CompPath = findComp.DistinguishedName;
              }
           }
        }
     }
      }
 }
开发者ID:vildar82,项目名称:AD-Computers-Users,代码行数:25,代码来源:Form1.cs


注:本文中的System.DirectoryServices.AccountManagement.PrincipalContext类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。