[C#] 利用Active Directory 作認證

利用Directory Service 管理user account 在很多公司也很常見. 尤其是Active Directory, 一套Microsoft 參考OpenLDAP 而成的Directory Service.

在.net Framework 中, 如何與Active Directory作認證, 無需打一段LDAP Query, 只須要利用System.DirectoryServices 去進行. 

public interface IAuthenticator
    {
        bool Authenticate(string userName, string password);
        IList<string> GetGroupsByUserAccount(string name);
    }

LdapAuthenticator.cs

 public class LdapAuthenticator : IAuthenticator
    {
        private string _domainName;
        public LdapAuthenticator(string domainName)
        {
            _domainName = domainName;
        }
        public bool Authenticate(string userName, string password)
        {
            bool result = false;
            using (LdapConnection ldapConnection = new LdapConnection(new LdapDirectoryIdentifier(String.Empty, false, false)))
            {
                NetworkCredential credential = new NetworkCredential(userName, password, _domainName);
                ldapConnection.Credential = credential;
                ldapConnection.AuthType = AuthType.Negotiate;
                ldapConnection.Bind(credential);
                result = true;
            }
            return result;
        }

        public IList<string> GetGroupsByUserAccount(string name)
        {
            IList<string> result = new List<string>();

            // Get user entry in LDAP.
            PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, _domainName);
            UserPrincipal userPrinciple = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, name);
            if (userPrinciple != null)
            {
                Console.WriteLine("User " + name + " found.");
                PrincipalSearchResult<Principal> userGroupPrincipals = userPrinciple.GetAuthorizationGroups();
                IEnumerator<Principal> iterator = userGroupPrincipals.GetEnumerator();
                using (iterator)
                {
                    while (iterator.MoveNext())
                    {
                        try
                        {
                            Principal groupPrincipal = iterator.Current;
                            result.Add(groupPrincipal.SamAccountName);
                        }
                        catch (NoMatchingPrincipalException ex)
                        {
                            continue;
                        }
                    }
                }
            }
            return result;
        }
    }

使用方法

 [TestMethod]
        public void TestMethod1()
        {
            IAuthenticator authenticator = new LdapAuthenticator("CompanyDomainName");
            Assert.IsTrue(authenticator.Authenticate("UserName", ""));
        }

而若想進行Single-sign-on 的話, 在.net 環境中, 只須叫用Environment 便可以存取登入使用者資訊.

Console.WriteLine("Current User Name: " + Environment.UserName);
Console.WriteLine("Current user domain: " + Environment.UserDomainName);
About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.