在 2.0 的時候,若要做 AD 驗證機制是使用 DirectoryServices 來進行實作,
但到了 3.5 ,要實作 AD 驗證比以往方便很多。
在實作之前需要將 System.DirectoryServices.AccountManagement.dll 加入參考
01 |
private static PrincipalContext _pc = null ; //宣告PrincipalContext |
02 |
/// <summary> |
03 |
/// 驗證帳密 |
04 |
/// </summary> |
05 |
/// <param name="validType">驗證型態</param> |
06 |
/// <param name="UserName">使用者名稱</param> |
07 |
/// <param name="PassWord">使用者密碼</param> |
08 |
/// <returns>驗證通過回傳真值</returns> |
09 |
public static Boolean CheckUser(ValidType validType, String UserName, String PassWord) |
10 |
{ |
11 |
try |
12 |
{ |
13 |
String[] UserArray = UserName.Split( new char [] { '\' }); //UserName 組合為 DomainAccount 或 MachineNameAccount |
14 |
InitPC(validType, UserArray[0]); |
15 |
Boolean isValid = _pc.ValidateCredentials(UserArray[1], PassWord); |
16 |
return isValid; |
17 |
} |
18 |
catch (Exception ex) |
19 |
{ |
20 |
String debug = ex.Message; |
21 |
return false ; |
22 |
} |
23 |
} |
01 |
/// <summary> |
02 |
/// PrincipalContext初始化 |
03 |
/// </summary> |
04 |
/// <param name="validType">驗證型態</param> |
05 |
/// <param name="LDAPName">網域/電腦名稱/應用程式名稱</param> |
06 |
static void InitPC(ValidType validType, String LDAPName) |
07 |
{ |
08 |
//PrincipalContext pc = null; |
09 |
int typeNum = ( int )validType; |
10 |
switch (typeNum) |
11 |
{ |
12 |
case 1: |
13 |
_pc = new PrincipalContext(ContextType.Domain, LDAPName); |
14 |
break ; |
15 |
case 2: |
16 |
_pc = new PrincipalContext(ContextType.Machine, LDAPName); |
17 |
break ; |
18 |
case 3: |
19 |
_pc = new PrincipalContext(ContextType.ApplicationDirectory, LDAPName); |
20 |
break ; |
21 |
default : |
22 |
break ; |
23 |
} |
24 |
25 |
/// <summary> |
26 |
/// 驗證型態列舉 |
27 |
/// </summary> |
28 |
public enum ValidType |
29 |
{ |
30 |
/// <summary> |
31 |
/// 網域 |
32 |
/// </summary> |
33 |
Domain = 1, |
34 |
/// <summary> |
35 |
/// 機器 |
36 |
/// </summary> |
37 |
Machine = 2, |
38 |
/// <summary> |
39 |
/// 應用程式 |
40 |
/// </summary> |
41 |
ApplicationDirectory = 3 |
42 |
} |
43 |
44 |
} |
http://www.dotblogs.com.tw/orhuang/archive/2010/07/21/16677.aspx