Skip to content

Instantly share code, notes, and snippets.

@LinZap
Created March 3, 2017 02:55
Show Gist options
  • Select an option

  • Save LinZap/5e5fe12c6bb785d1b7c1f9b372b84c4f to your computer and use it in GitHub Desktop.

Select an option

Save LinZap/5e5fe12c6bb785d1b7c1f9b372b84c4f to your computer and use it in GitHub Desktop.
AD 帳號整合 (use C#)
using System;
using System.DirectoryServices;
using System.Diagnostics;
public class AD
{
private string server;
public AD(string server)
{
this.server = server;
}
public bool isAuth(string act, string pwd)
{
DirectoryEntry ent = new DirectoryEntry(server, act, pwd);
DirectorySearcher ds = new DirectorySearcher(ent);
ds.Filter = "(sAMAccountName=" + act + ")";
ds.PropertiesToLoad.Add("mail");
ds.PropertiesToLoad.Add("displayname");
try
{
SearchResult sr = ds.FindOne();
if (sr == null)
{
Trace.WriteLine("No account");
return false;
}
else
{
string atest = getVal(sr,"displayname");
string mail = getVal(sr, "mail");
Trace.WriteLine(string.Format("Hi~ {0}, email: {1}", atest, mail));
return true;
}
}
catch (Exception e)
{
Trace.WriteLine(e.ToString());
return false;
}
}
private string getVal(SearchResult sr,string key) {
try {
return sr.GetDirectoryEntry().Properties[key].Value.ToString();
}
catch (Exception) {
return "";
}
}
}
public class ADTests
{
[TestMethod()]
public void isAuth()
{
AD ad = new AD("LDAP://rusebot.com:389");
bool res = ad.isAuth("帳號", "密碼");
Assert.IsTrue(res);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment