Windows 域验证

  
    
1 using System;
2   using System.Data;
3 using System.Configuration;
4 using System.Web;
5 using System.Web.Security;
6 using System.Web.UI;
7 using System.Web.UI.WebControls;
8 using System.Web.UI.WebControls.WebParts;
9 using System.Web.UI.HtmlControls;
10 using System.Runtime.InteropServices; // 必要引用
11 using System.Security.Principal; // 必要引用
12 /**/ /// <summary>
13 /// UserLoginForDomain 的摘要说明
14 /// 适用ASP.NET 2.0
15 /// Windows XP 调试成功
16 /// 调用”advapi32.dll“win32 API
17 /// </summary>
18
19 namespace UserLoginForDomain
20 {
21 public class UserLoginForDomainDAO
22 {
23 public const int LOGON32_LOGON_INTERACTIVE = 2 ;
24 public const int LOGON32_PROVIDER_DEFAULT = 0 ;
25
26 WindowsImpersonationContext impersonationContext;
27
28 [DllImport( " advapi32.dll " , CharSet = CharSet.Auto)]
29 public static extern int LogonUser(String lpszUserName,
30 String lpszDomain,
31 String lpszPassword,
32 int dwLogonType,
33 int dwLogonProvider,
34 ref IntPtr phToken);
35 [DllImport( " advapi32.dll " , CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true )]
36 public extern static int DuplicateToken(IntPtr hToken,
37 int impersonationLevel,
38 ref IntPtr hNewToken);
39 /**/
40 /// <summary>
41 /// 输入用户名、密码、登录域判断是否成功
42 /// </summary>
43 /// <example>
44 /// if (impersonateValidUser(UserName, Domain, Password)){}
45 /// </example>
46 /// <param name="userName"> 账户名称,如:string UserName = UserNameTextBox.Text; </param>
47 /// <param name="domain"> 要登录的域,如:string Domain = DomainTextBox.Text; </param>
48 /// <param name="password"> 账户密码, 如:string Password = PasswordTextBox.Text; </param>
49 /// <returns> 成功返回true,否则返回false </returns>
50 public bool impersonateValidUser(String userName, String domain, String password)
51 {
52 WindowsIdentity tempWindowsIdentity;
53 IntPtr token = IntPtr.Zero;
54 IntPtr tokenDuplicate = IntPtr.Zero;
55
56 if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
57 LOGON32_PROVIDER_DEFAULT, ref token) != 0 )
58 {
59 if (DuplicateToken(token, 2 , ref tokenDuplicate) != 0 )
60 {
61 tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
62 impersonationContext = tempWindowsIdentity.Impersonate();
63 if (impersonationContext != null )
64 return true ;
65 else
66 return false ;
67 }
68 else
69 return false ;
70 }
71 else
72 return false ;
73 }
74
75 public void undoImpersonation()
76 {
77 impersonationContext.Undo();
78 }
79 //
80 // TODO: 在此处添加构造函数逻辑
81 //
82 }
83
84
85 }
86

 

你可能感兴趣的:(windows)