C# AD域用户登录验证

2022/7/28 1:24:05

本文主要是介绍C# AD域用户登录验证,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

    /// <summary>
    /// AD域验证服务
    /// </summary>
    public static class ActiveDirectoryService
    {
        //轻型目录访问协议
        private static readonly string agreement = "LDAP://"; 
        //DNS AD域名 域地址
        private static readonly string ADPath = "192.168.9.9";
        //管理员用户名
        private static readonly string ADAccount = "user";
        //管理员密码
        private static readonly string AdPwd = "234567t";
        //禁用用户帐户
        private static readonly int ACCOUNTDISABLE = 0x0002;

        /// <summary>
        /// 根据用户名进行AD域登录校验
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public static string ActiveDirectoryLogin(string UserName)
        {
            
            using (DirectoryEntry adsEntry = new DirectoryEntry(agreement + ADPath, ADAccount, AdPwd, AuthenticationTypes.Secure))
            {
                if (adsEntry is null)
                {
                    Console.WriteLine("test");
                }
                using (DirectorySearcher adsSearch = new DirectorySearcher(adsEntry))
                {
                    adsSearch.Filter = "(&(objectCategory=user)(sAMAccountName=" + UserName + "))";

                    SearchResultCollection adsSearchResult = adsSearch.FindAll();

                    //判断域用户是否存在
                    if (adsSearchResult.Count != 0 )
                    {

                        using (DirectoryEntry deEntity = new DirectoryEntry(adsSearch.FindOne().Path, ADAccount, AdPwd, AuthenticationTypes.Secure))
                        {
                            int ADUserDisabled = Convert.ToInt32(ACCOUNTDISABLE);

                            int flagExists = Convert.ToInt32(deEntity.Properties["userAccountControl"][0]) & ADUserDisabled;

                            if (flagExists > 0)
                            {
                                return "域用户已被禁用,不可登录";
                            }
                            else
                            {
                                return null;
                            }
                        } 

                    }
                    else
                    {
                        return "域用户不存在,不可登录";
                    }
                }
            }
        }

    }

 



这篇关于C# AD域用户登录验证的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程