當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。