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());
			}
		}
 /// <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);
     }
 }
Ejemplo n.º 3
0
        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;
        }
        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;
        }
Ejemplo n.º 5
0
        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;
        }
        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;
        }
Ejemplo n.º 7
0
        public EntityResponse<User> Login(LoginRequest credentials)
        {
            var response = new EntityResponse<User> {EntityType = typeof (User).ToString()};

            // set up domain context
            var ctx = new PrincipalContext(ContextType.Domain);

            if (ctx.ValidateCredentials(credentials.UserName, credentials.Password))
            {
                var user = UserPrincipal.FindByIdentity(ctx, credentials.UserName);

                if (user != null)
                {
                    var u = new User
                    {
                        Email = user.EmailAddress,
                        DisplayName = user.DisplayName,
                        UserName = credentials.UserName
                    };

                    response.ResponseCode = ResponseCode.Success;
                    response.Message = ResponseMessage.Success;
                    response.Data = u;
                }
                else
                {
                    SetResponseError(ref response);
                }
            }
            else
                SetResponseError(ref response);

            return response;
        }
        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
                };
            }
        }
 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;
 }
Ejemplo n.º 10
0
        /// <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;
                }
            }
        }
Ejemplo n.º 11
0
 protected override bool _Validate()
 {
     using (var adContext = new PrincipalContext (ContextType.Domain, "ad.okstate.edu"))
     {
         return adContext.ValidateCredentials (user, pass);
     }
 }
 private static bool WindowsAuthenticate(string usuario, string senha)
 {
     using (var context = new PrincipalContext(ContextType.Machine, "nomedasuamaquina"))
     {
         return context.ValidateCredentials(usuario, senha);
     }
 }
 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();
     }
 }
Ejemplo n.º 14
0
 /// <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;
     }
 }
Ejemplo n.º 15
0
 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;
 }
Ejemplo n.º 16
0
        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;
            }
        }
Ejemplo n.º 17
0
        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",
            });
        }
Ejemplo n.º 18
0
        public StringBuilder Execute(Dictionary<string, StringBuilder> values, IWorkspace theWorkspace)
        {
            string domain = null;
            string username = null;
            string password = null;

            StringBuilder tmp;
            values.TryGetValue("Domain", out tmp);
            if(tmp != null)
            {
                domain = tmp.ToString();
            }

            values.TryGetValue("Username", out tmp);

            if(tmp != null)
            {
                username = tmp.ToString();
            }

            values.TryGetValue("Password", out tmp);

            if(tmp != null)
            {
                password = tmp.ToString();
            }


            if(string.IsNullOrEmpty(domain) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                throw new InvalidDataContractException("Domain or Username or Password is missing");
            }

            var result = new ExecuteMessage { HasError = false };

            try
            {
                if(domain.Equals("."))
                {
                    domain = Environment.UserDomainName;
                }
                bool isValid;
                using(var context = new PrincipalContext(ContextType.Domain, domain))
                {
                    isValid = context.ValidateCredentials(username, password);

                    context.Dispose();
                }
                result.SetMessage(isValid ? "<result>Connection successful!</result>" : "<result>Connection failed. Ensure your username and password are valid</result>");
            }
            catch
            {
                result.SetMessage("<result>Connection failed. Ensure your username and password are valid</result>");
            }

            Dev2JsonSerializer serializer = new Dev2JsonSerializer();

            return serializer.SerializeToBuilder(result);
        }
 public bool ValidateUser(string username, string password)
 {
     using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
     {
         // validate the credentials
         return pc.ValidateCredentials(username, password);
     }
 }
Ejemplo n.º 20
0
 public bool Login(string password)
 {
     using (PrincipalContext pc = new PrincipalContext(ContextType.Machine))
     {
         _isValid = pc.ValidateCredentials(Environment.UserName, password);
     }
     return _isValid;
 }
Ejemplo n.º 21
0
 public bool Validate(string login, string pass)
 {
     using (var context = new System.DirectoryServices.AccountManagement.PrincipalContext(ContextType.Domain, DOMAIN, null, null))
     {
         //Username and password for authentication.
         return(context.ValidateCredentials(login, pass));
     }
 }
Ejemplo n.º 22
0
 public bool ValidateCredentials(string domain, string user, string pass)
 {
     using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domain))
     {
         // validate the credentials
         return context.ValidateCredentials(user, pass);
     }
 }
Ejemplo n.º 23
0
 public bool Authenticate(string usuario, string password)
 {
     //using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, LDAP_DOMAIN, LDAP_USER, LDAP_PASSWORD))
     using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, LDAP_DOMAIN))
     {
         return pc.ValidateCredentials(usuario, password);
     }
 }
Ejemplo n.º 24
0
 public bool Authenticate(string username, string password)
 {
     bool isvalid = false;
     using(var pc = new PrincipalContext(ContextType.Domain, "pts18"))
     {
         isvalid = pc.ValidateCredentials(username, password);
     }
     return isvalid;
 }
Ejemplo n.º 25
0
 public bool ValidateLogin(string userName, string password, string domainName = "")
 {
     bool valid;
     using (var context = new PrincipalContext(ContextType.Domain))
     {
         valid = context.ValidateCredentials(userName, password);
     }
     return valid;
 }
Ejemplo n.º 26
0
 public static bool authenticateOnLocalMachiche(string username, string password)
 {
     bool valid = false;
     using (PrincipalContext context = new PrincipalContext(ContextType.Machine))
     {
         valid = context.ValidateCredentials( username, password );
     }
     return valid;
 }
Ejemplo n.º 27
0
        public bool Validate(string login, string pass)
        {
            using (var context = new System.DirectoryServices.AccountManagement.PrincipalContext(ContextType.Domain, DOMAIN, null, null))
            {

                //Username and password for authentication.
                return context.ValidateCredentials(login, pass);
            }
        }
 public static bool VerifyDomainUserAccount(string domain, string username, string password)
 {
     Logger.Instance.Debug("Verify domain account, domain:{0}, user:{1}", domain, username);
     using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain))
     {
         // validate the credentials
         return pc.ValidateCredentials(username, password, ContextOptions.Negotiate);
     }
 }
        public ValidationResult ValidateUser(string username, string password)
        {
            ValidationResult result = ValidationResult.Failure;

            if (String.IsNullOrEmpty(username)) throw new ArgumentException("Value cannot be null or empty", "userName");
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty", "password");

            try
            {
                string domain = GetDomainFromUsername(username);
                if (String.IsNullOrEmpty(domain))
                {
                    domain = Configuration.ActiveDirectorySettings.DefaultDomain;
                }

                using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domain))
                {
                    if (principalContext.ValidateCredentials(username, password))
                    {
                        using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, username))
                        {
							using (GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, Configuration.ActiveDirectorySettings.MemberGroupName))
							{
								if (group == null)
									result = ValidationResult.Failure;

								if (user != null)
								{
									if (!group.GetMembers(true).Contains(user))
									{
										result = ValidationResult.NotAuthorized;
									}
									else
									{
										ADBackend.Instance.Users.AddOrUpdate(new UserModel
										{
											Name = user.UserPrincipalName,
											GivenName = user.GivenName ?? String.Empty,
											Surname = user.Surname ?? String.Empty,
											Email = user.EmailAddress ?? String.Empty,
										});
										result = ValidationResult.Success;
									}
								}
							}
                        }
                    }
                }
            }
            catch
            {
                result = ValidationResult.Failure;
            }

            return result;
        }
        public static bool VerifyMachineUserAccount(string machineName, string username, string password)
        {
            Logger.Instance.Debug("Verify machine account, domain:{0}, user:{1}", machineName, username);

            using (PrincipalContext pc = new PrincipalContext(ContextType.Machine, machineName))
            {
                // validate the credentials
                return pc.ValidateCredentials(username, password);
            }
        }
Ejemplo n.º 31
0
        public static Boolean checkPw(String username, String password)
        {
            if (password == String.Empty)
                return false;

            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, DOMAIN))
            {
                Boolean isValid = pc.ValidateCredentials(username, password);
                return isValid;
            }
        }
Ejemplo n.º 32
0
        //private string sDomain = ConfigurationManager.AppSettings["sDomain"];
        //private string sDefaultOU = ConfigurationManager.AppSettings["sDefaultOU"];
        //private string sDefaultRootOU = ConfigurationManager.AppSettings["sDefaultRootOU"];
        //private string sServiceUser = ConfigurationManager.AppSettings["sServiceUser"];
        //private string sServicePassword = ConfigurationManager.AppSettings["sServicePassword"];

        //private string sDomain = "test.com";
        //private string sDefaultOU = "OU=Test Users,OU=Test,DC=test,DC=com";
        //private string sDefaultRootOU = "DC=test,DC=com";
        //private string sServiceUser = @"ServiceUser";
        //private string sServicePassword = "******";

        #endregion

        #region Methods

        /// <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>
        private bool ValidateCredentials(string sUserName, string sPassword)
        {
            PrincipalContext oPrincipalContext = GetPrincipalContext();

            return(oPrincipalContext.ValidateCredentials(sUserName, sPassword));
        }