• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# AccountManagement.PrincipalContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: Authenticate

        public IHttpActionResult Authenticate(AuthenticationRequest authRequest)
        {
            bool valid = false;
            using (var context = new PrincipalContext(ContextType.Machine))
            {
                if (Principal.FindByIdentity(context, authRequest.Username) != null)
                {
                    valid = context.ValidateCredentials(authRequest.Username, authRequest.Password);
                }
            }

            if (valid)
            {
                OpaqueSecurityToken token = new OpaqueSecurityToken();

                token.SecurePayload[OpaqueSecurityToken.KnownPayloadKeys.USERNAME] = authRequest.Username;
                token.SecurePayload[OpaqueSecurityToken.KnownPayloadKeys.TTL_SEC] = (60 * 60).ToString(); // 1 hour

                return Ok(new AuthenticationResponse()
                {
                    AuthToken = token.SerializeToString(),
                    AuthType  = AuthMessageHandler.AuthenticationType,
                });
            }

            //throw new HttpResponseException(HttpStatusCode.Unauthorized);

            return Content((HttpStatusCode)422, new AuthenticationResponse()
            {
                ErrorMessage = "Invalid username or password",
            });
        }
开发者ID:gubenkoved,项目名称:photo-galery,代码行数:32,代码来源:UserController.cs


示例17: GetSpecialistList

        public static IEnumerable<KeyValuePair<string, string>> GetSpecialistList(AdGroup grp)
        {
            var list = new Dictionary<string, string>();

            using (WindowsImpersonationContextFacade impersonationContext
                = new WindowsImpersonationContextFacade(
                    nc))
            {
                var domain = new PrincipalContext(ContextType.Domain);
                var group = GroupPrincipal.FindByIdentity(domain, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(grp));
                if (group != null)
                {
                    var members = group.GetMembers(true);
                    foreach (var principal in members)
                    {
                        var userPrincipal = UserPrincipal.FindByIdentity(domain, principal.SamAccountName);
                        if (userPrincipal != null)
                        {
                            var name = MainHelper.ShortName(userPrincipal.DisplayName);
                            var sid = userPrincipal.Sid.Value;
                            list.Add(sid, name);
                        }
                    }
                }

                return list.OrderBy(x => x.Value);
            }
        }
开发者ID:WakeDown,项目名称:UnitApis,代码行数:28,代码来源:AdHelper.cs


示例18: ProcessOk

 private void ProcessOk()
 {
     try
     {
         PrincipalContext pcontext = new PrincipalContext(this.contextType, this.domain);
         using (pcontext)
         {
             if (pcontext.ValidateCredentials(this.user, this.textBoxPassword.Text, this.contextOptions) == false)
             {
                 this.labelPassword.ForeColor = System.Drawing.Color.DarkRed;
                 this.textBoxPassword.BackColor = System.Drawing.Color.Coral;
                 this.pictureBoxLock.Visible = true;
                 this.textBoxPassword.Select();
             }
             else
             {
                 this.password = this.textBoxPassword.Text;
                 this.labelPassword.ForeColor = System.Drawing.Color.DarkGreen;
                 this.textBoxPassword.BackColor = System.Drawing.Color.WhiteSmoke;
                 this.pictureBoxLock.Visible = false;
                 this.pictureBoxOpenLock.Visible = true;
                 this.Refresh();
                 System.Threading.Thread.Sleep(400);
                 this.Close();
             }
         }
     }
     catch (Exception ex)
     {
         this.exception = ex;
         this.Close();
     }
 }
开发者ID:simondmorias,项目名称:MSBuildExtensionPack,代码行数:33,代码来源:GetPasswordForm.cs


示例19: ChangePassword

 public static bool ChangePassword(string sUserName, string oldPassword, string newPassword)
 {
     try
     {
         if (string.IsNullOrEmpty(ADISConstants.DomainOU))
         {
             using (var context = new PrincipalContext(ContextType.Domain, ADISConstants.DomainNameOrIP, sUserName, oldPassword))
             {
                 using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, sUserName))
                 {
                     //user.SetPassword("newpassword");
                     // or
                     user.ChangePassword(oldPassword, newPassword);
                 }
             }
         }
         else
         {
             using (var context = new PrincipalContext(ContextType.Domain, ADISConstants.DomainNameOrIP, ADISConstants.DomainOU, sUserName, oldPassword))
             {
                 using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, sUserName))
                 {
                     //user.SetPassword("newpassword");
                     // or
                     user.ChangePassword(oldPassword, newPassword);
                 }
             }
         }
         return true;
     }
     catch(Exception ex)
     {
         throw ex;
     }
 }
开发者ID:khoainv,项目名称:Framework,代码行数:35,代码来源:ADUserService.cs


示例20: SetClientRole

 internal static bool SetClientRole(string loginName, BplRole role) {
    var result = false;
    try {
       using (var context = new PrincipalContext(ContextType.Domain, ADServer, ADUserContainer, ADUsername, ADPassword)) {
          var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, loginName);
          if (user != null) {
             var gpRole = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, (string)role.Id.LocalId);
             if (gpRole != null) {
                var grp = (DirectoryEntry)gpRole.GetUnderlyingObject();
                grp.Properties["member"].Add(user.DistinguishedName);
                grp.CommitChanges();
                grp.Close();
                result = true;
             } else {
                Log.Warn("Auth: Group for role {0} was not found.", role.Id);
             }
          } else {
             Log.Warn("Auth: User {0} was not found.", loginName);
          }
       }
    } catch (Exception e) {
       Log.Exception(e, "Auth: Unable to set roles to user '{0}'", loginName);
    }
    return result;
 }
开发者ID:borkaborka,项目名称:gmit,代码行数:25,代码来源:AuthServices.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# AccountManagement.UserPrincipal类代码示例发布时间:2022-05-26
下一篇:
C# DirectoryServices.DirectorySearcher类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap