Force user to change password on first login in Active Directory using C#


If user Login first time then force user to change password on first Login

 public bool FirstTimeUser(string userName, string Password, string domain)
        {

            try
            {
                string ldapPath = LDapUrl;
                DirectoryEntry directionEntry = new DirectoryEntry(ldapPath, domain + "\\" + userName, Password);
                if (directionEntry != null)
                {
                    DirectorySearcher search = new DirectorySearcher(directionEntry);

                    search.Filter = "(SAMAccountName=" + userName + ")";
                    using (var pctx = new PrincipalContext(ContextType.Domain))
                    {

                        using (var p = UserPrincipal.FindByIdentity(pctx, IdentityType.SamAccountName, userName))
                        {
                            if (p == null)
                                return false;
                            bool ISPasswordCorrect = pctx.ValidateCredentials(userName, Password, ContextOptions.Negotiate);

                            if (p.LastPasswordSet.HasValue == false && p.PasswordNeverExpires == false)
                            {                              
                                Session["UserName"] = userName; // pass user name in session and get it on another page
                                Response.Redirect("Default.aspx?ChangePasswordOnFirstLogin=yes");
                            }
                            else if (ISPasswordCorrect == false)
                            {
                               lblErrormsg.Visible = true;
                               lblErrormsg.Text = "The username or password is incorrect";
                            }

                        }
                    }

                }

            }


            catch (MultipleMatchesException mmex)
            {
                string errorMsg;
                errorMsg = "TestAdShouldChangePassword( ad user = '" + userName + "' ) - Exception finding user, can't determine if ad says to change password, returing false : Ex = " + mmex.Message;

            }

            return false;
        }

No comments:

Post a Comment