C# User LDAP 帳號密碼驗證

之前寫過「[.NET]CALL AD驗証密碼」,

但最近遇到的客戶是使用 Open LDAP Server,

就驗證不過了,所以我們可以透過「 LdapConnection 」這個物件來幫我們驗證哦!

程式如下,

//using System.Net;
//using System.DirectoryServices;
//using System.DirectoryServices.Protocols;
//using System.Security.Permissions;
//加入DLL參考:System.DirectoryServices, System.DirectoryServices.Protocols
static bool ValidateLDAPUser(string ldapserver, string port, string userId, string password)
{
	try
	{
		using (var ldapConnection = new LdapConnection(
				new LdapDirectoryIdentifier($"{ldapserver}:{port}")))
		{
			ldapConnection.AuthType = AuthType.Basic;
			ldapConnection.AutoBind = false;
			ldapConnection.Timeout = new TimeSpan(0, 0, 0, 15);
			//這裡可能每個組織不同哦!
			var ldapUserId = $"uid={userId},ou=people,dc=gss,dc=com";
			var credential = new NetworkCredential(ldapUserId, password);
			ldapConnection.Bind(credential);
			Console.WriteLine("Successfully authenticated to ldap server " + ldapserver);
			return true;
		}

	}
	catch (LdapException e)
	{
		Console.WriteLine(("Error with ldap server " + ldapserver + e.ToString()));
		return false;
	}
}

 

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^