2015年8月12日 星期三

.NET MVC - Active Directory Login 【AD登入驗證】Windows Server 2012 R2

public ActionResult Login(string UserName, string Password, string returnUrl)
        {
            string user = UserName + domain;

            //string pathStr = string.Format("LDAP://{0}{1}{2}", ip, port, baseDN);

            try
            {
                DirectoryEntry de = new DirectoryEntry("LDAP://192.168.64.128:389/OU=MyMemberServers,DC=eSecure,DC=com", user, Password);
                Guid guid = de.Guid;
                //DirectorySearcher ds = new DirectorySearcher(de);
                de.Dispose();
                return View("ChangePassword");
            }
            catch (Exception)
            {
                
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ip, inputBaseDN, admUser+domain, admPwd);

                UserPrincipal userObj = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, UserName);



                if (userObj != null)
                {
                    //帳號停用,userObj.Enabled可能為null true false
                    bool? isEnable = userObj.Enabled;
                    //isEnable = null;
                    if (!isEnable.HasValue)
                    {
                        ViewBag.Message = "系統發生錯誤,請聯絡系統管理員";
                    }
                    else if ((bool)!isEnable)
                    {
                        ViewBag.Message = "帳號已停用,請聯絡系統管理員";
                    }
                    else
                    {
                        bool isLockedOut = userObj.IsAccountLockedOut();
                        if (isLockedOut)
                        {
                            ViewBag.Message = "帳號已被鎖定,請聯絡系統管理員";
                        }
                        else
                        {
                            Int32 badLogonCount = userObj.BadLogonCount;
                            ViewBag.Message = "密碼錯誤" + badLogonCount + "次,錯誤3次帳號即被鎖定";
                        }
                    }
                    return View("Login");
                }
                ctx.Dispose();

                ViewBag.Message = "查無此帳號";
                return View("Login");
            }
        }

沒有留言:

張貼留言