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


C# PrincipalContext.ValidateCredentials方法代码示例

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


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

示例1: 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

示例2: Authenticate

 /// <summary>
 ///     Authenticates a user agains ad
 /// </summary>
 /// <param name="username">User name</param>
 /// <param name="password">password to check</param>
 /// <returns>User is ìauthenticated</returns>
 public static bool Authenticate(string username, string password)
 {
     var domain = ConfigurationManager.AppSettings["adDomain"];
     using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain))
     {
         return pc.ValidateCredentials(domain + "\\" + username, password) || pc.ValidateCredentials(username, password);
     }
 }
开发者ID:BazookaDeploy,项目名称:Bazooka,代码行数:14,代码来源:ActiveDirectoryAuthentication.cs

示例3: AuthWindows

        private static bool AuthWindows(string password)
        {
            var authenticated = false;
            var envName = Tools.GetUsernameAsService();
           
            var username = Environment.UserDomainName + "\\" + envName;
            //this will fix most domain logins, try first

            using (var context = new PrincipalContext(ContextType.Machine))
            {
                authenticated = context.ValidateCredentials(username, password);
            }
            //lets try a controller 
            if (!authenticated)
            {
                try
                {
                  
                    var domainContext = new DirectoryContext(DirectoryContextType.Domain, Environment.UserDomainName,
                        username, password);

                    var domain = Domain.GetDomain(domainContext);
                    var controller = domain.FindDomainController();
                    //controller logged in if we didn't throw.
                    authenticated = true;
                }
                catch (Exception)
                {
                    authenticated = false;
                }
            }
            return authenticated;
        }
开发者ID:Ulterius,项目名称:server,代码行数:33,代码来源:AuthUtils.cs

示例4: WindowsAuthenticate

 private static bool WindowsAuthenticate(string usuario, string senha)
 {
     using (var context = new PrincipalContext(ContextType.Machine, "nomedasuamaquina"))
     {
         return context.ValidateCredentials(usuario, senha);
     }
 }
开发者ID:bennotti,项目名称:Exemplo-Blog-Windows-And-Forms-Auth-ASPNET,代码行数:7,代码来源:ContaController.cs

示例5: Unnamed1_Authenticate

        protected void Unnamed1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            bool valid = false;
            using (var context = new PrincipalContext(ContextType.Domain))
            {
                var login = sender as System.Web.UI.WebControls.Login;
                if (login != null)
                {
                    valid = context.ValidateCredentials(login.UserName, login.Password);
                    if (valid)
                    {
                        var dal = new UsersDal();
                        var loginWithDomain = AuthProvider.LoginWithDomain(login.UserName);

                        if (!dal.IsUserExists(AuthProvider.LoginWithDomain(login.UserName)))
                        {
                            Session["CurrentUserId"] = dal.RegisterNewUser(loginWithDomain,
                                                         AuthProvider.GetUserFullNameByDomainIdentity(login.UserName));
                            Login1.DestinationPageUrl = "Profile.aspx";
                            //e.Authenticated = false;
                            //return;
                        }
                        else
                        {
                            Session["CurrentUserId"] = (new UsersDal()).GetUserGUIDByLogin(loginWithDomain);
                        }
                        Session["CurrentUser"] = loginWithDomain;

                        dal.UsersStatisticsUpdateLoginCount(AuthProvider.UserKey(Session));

                    }
                }
            }
            e.Authenticated = valid;
        }
开发者ID:Letractively,项目名称:dc-gamification,代码行数:35,代码来源:Login.aspx.cs

示例6: GetMembers

        public IEnumerable<IPrincipalDetails> GetMembers(string domainName, string username, string password, string groupName)
        {
            List<PrincipalDetails> results = new List<PrincipalDetails>();

            using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName, username, password))
            {
                if (!string.IsNullOrEmpty(username))
                {
                    bool valid = context.ValidateCredentials(username, password);
                    if (!valid)
                        throw new SecurityException(null, "Unable to authenticate with '{0}' using '{1}'", domainName, username);
                }

                try
                {
                    using (GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, groupName))
                    {
                        // FindByIdentity returns null if no matches were found
                        if (group == null)
                            throw new InvalidOperationException(string.Format("The group {0} could not be found", groupName));

                        // Add all of the members of this group, and any sub-group to the list of members.
                        AddGroupMembers(group, results);
                    }
                }
                catch (Exception ex)
                {
                    throw new SecurityException(ex, "Unable to query Active Directory.");
                }
            }

            return results;
        }
开发者ID:NaseUkolyCZ,项目名称:roadkill,代码行数:33,代码来源:ActiveDirectoryProvider.cs

示例7: authenticateUser

 /// <summary>
 /// Authenticates with Active Directory and returns a populated userContext object if authentication is successful
 /// </summary>
 /// <param name="userName"></param>
 /// <param name="password"></param>
 /// <returns></returns>
 public static userContext authenticateUser(string userName, string password)
 {
     try
     {
         userContext uContext = new userContext();
         bool authenticated = false;
         PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, Properties.Settings.Default.domain, Properties.Settings.Default.domainLDAPbase);
         authenticated = domainContext.ValidateCredentials(userName, password, ContextOptions.Negotiate);
         if (authenticated)
         {
             uContext.loggedOn = true;
             uContext.SAMAccount = userContext.getUserAccount(userName);
             uContext.currentUserAuthorizationGroups = userContext.getGroups(userName);
         }
         else
         {
             uContext.loggedOn = false;
         }
         return uContext;
     }
     catch (System.DirectoryServices.DirectoryServicesCOMException ex)
     {
         throw ex;
     }
 }
开发者ID:macnlinux,项目名称:userManagement,代码行数:31,代码来源:userContext.cs

示例8: 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

示例9: Validate

        public DirectoryEntry Validate(string username, string password)
        {
            var config = Config.Get<Settings>();
            using (var context = new PrincipalContext(ContextType.Domain, config.Domain))
            {
                bool isValid;
                try
                {
                    isValid = context.ValidateCredentials(username, password, ContextOptions.Negotiate);
                }
                catch (Exception ex)
                {
                    Log.Error("Error authenticating user", ex, this.GetType());
                    return null;
                }

                if (!isValid)
                    return null;

                var identity = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
                return new DirectoryEntry
                {
                    Username = identity.SamAccountName,
                    Email = identity.EmailAddress.TrimToNull(),
                    FirstName = identity.GivenName,
                    LastName = identity.Surname
                };
            }
        }
开发者ID:fzhenmei,项目名称:Chriz.Serene,代码行数:29,代码来源:ActiveDirectoryService.cs

示例10: Validate

        public bool Validate(string userName, string password, out ClaimsIdentity oAuthIdentity, out ClaimsIdentity cookiesIdentity)
        {
            using (var ctx = new PrincipalContext(ContextType.Domain, DomainName))
            {
                bool isValid = ctx.ValidateCredentials(userName, password);
                if (isValid)
                {
                    oAuthIdentity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
                    cookiesIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationType);
                    var groups=GetUserGroups(userName);
                    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, userName));
                    cookiesIdentity.AddClaim(new Claim(ClaimTypes.Name, userName));

                    if (groups.Contains("BD"))
                    {
                        oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "BD"));
                        cookiesIdentity.AddClaim(new Claim(ClaimTypes.Role, "BD"));
                    }
                    else
                    {
                        oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, string.Join(",", groups)));
                        cookiesIdentity.AddClaim(new Claim(ClaimTypes.Role, string.Join(",", groups)));
                    }

                }
                else
                {
                    oAuthIdentity = null;
                    cookiesIdentity = null;
                }

                return isValid;
            }
        }
开发者ID:changLiuUNSW,项目名称:BDSystem,代码行数:34,代码来源:AuthRepository.cs

示例11: ADValidate

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected void ADValidate(AuthenticateEventArgs e)
        {
            var domainForValidation = ConfigurationManager.AppSettings["IsHammerTime"] == "True"
                ? "BOMP" : ConfigurationManager.AppSettings["DomainForValidation"];

            using (var pc = new PrincipalContext(ContextType.Domain, domainForValidation))
            {
                //validate the credentials
                try
                {
                    var isValid = pc.ValidateCredentials(LoginUser.UserName, LoginUser.Password);

                    if (!isValid) return;
                    Session.Add("credential",LoginUser.Password);

                    e.Authenticated = true;
                    var usuario = GetCredentialFromDb();
                    if (usuario != null)
                        CreateEncryptedTicket(e, usuario.NombreCompleto);
                    else
                    {
                        LoginUser.FailureText = "El usuario no tiene permisos para acceder a la aplicación.";
                        e.Authenticated = false;
                    }
                }
                catch (Exception exception)
                {
                    LoginUser.FailureText = exception.Message;
                    e.Authenticated = false;
                }
            }
        }
开发者ID:Avaruz,项目名称:SGC,代码行数:36,代码来源:Login.aspx.cs

示例12: Login

 public string Login(string password, WebSocket clientSocket)
 {
     var code = 3;
     if (string.IsNullOrEmpty(password))
     {
         code = INVALID_PASSWORD;
     }
     using (var context = new PrincipalContext(ContextType.Machine))
     {
         code = context.ValidateCredentials(GetUsername(), password) ? 2 : 3;
     }
     var authenticated = code == AUTHENTICATED;
     foreach (var client in TaskManagerServer.AllClients.Where(client => client.Value.Client == clientSocket))
     {
         if (code == INVALID_PASSWORD)
         {
             client.Value.Authenticated = false;
         }
         else if (code == AUTHENTICATED)
         {
             client.Value.Authenticated = true;
         }
     }
     var authenticationData = new JavaScriptSerializer().Serialize(new
     {
         endpoint = "authentication",
         results = new
         {
             authenticated,
             message = authenticated ? "Login was successfull" : "Login was unsuccessful"
         }
     });
     return authenticationData;
 }
开发者ID:cron410,项目名称:ulterius-server,代码行数:34,代码来源:UlteriusLoginDecoder.cs

示例13: 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

示例14: _Validate

 protected override bool _Validate()
 {
     using (var adContext = new PrincipalContext (ContextType.Domain, "ad.okstate.edu"))
     {
         return adContext.ValidateCredentials (user, pass);
     }
 }
开发者ID:noblethrasher,项目名称:Credentials,代码行数:7,代码来源:OkeyCredentials.cs

示例15: validateUser

        public bool validateUser(string username, string password)
        {
            string UN = username;
            string PW = password;
            bool state;
            bool inGrp = false;

            PrincipalContext Context = new PrincipalContext(ContextType.Domain, "wallworkinc.com");
            GroupPrincipal group = GroupPrincipal.FindByIdentity(Context, "Help Desk Admins");

            state = Context.ValidateCredentials(UN, PW);
            if (state != false)
            {
                foreach (Principal principal in group.Members)
                {
                    string name = principal.SamAccountName;
                    if (name == UN)
                    {
                        inGrp = true;
                    }
                }
            }
            else
            {
                inGrp = false;
            }
            return inGrp;
        }
开发者ID:AustinSkarphol,项目名称:WallworkProjects,代码行数:28,代码来源:Login+(Austin-PC's+conflicted+copy+2013-02-12).cs


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