WebPart模拟用户验证
既是用另一个用户来代替当前用户行使特殊操作(一般是当前用户不能行使的操作)
具体操作:
1。WindowsImpersonationContext wic = ChangeUser.CreateIdentity(this.UserName, this.UserDomain, this.UserPassWord).Impersonate();
WindowsImpersonationContext 表示模拟操作之前的 Windows 用户。
ChangeUser.CreateIdentity() 登陆新的用户。
2。执行要做的特殊操作。
3。 wic.Undo(); 将用户上下文恢复为该对象表示的 Windows 用户。
ChangeUser.CreateIdentity()的实现
既是用另一个用户来代替当前用户行使特殊操作(一般是当前用户不能行使的操作)
具体操作:
1。WindowsImpersonationContext wic = ChangeUser.CreateIdentity(this.UserName, this.UserDomain, this.UserPassWord).Impersonate();
WindowsImpersonationContext 表示模拟操作之前的 Windows 用户。
ChangeUser.CreateIdentity() 登陆新的用户。
2。执行要做的特殊操作。
3。 wic.Undo(); 将用户上下文恢复为该对象表示的 Windows 用户。
ChangeUser.CreateIdentity()的实现
1
using System;
2
using System.Security.Principal;
3
using System.Runtime.InteropServices;
4
namespace UsageInfo
5

{
6
/**//// <summary>
7
/// ChangeUser 的摘要说明。
8
/// </summary>
9
public class ChangeUser
10
{
11
public ChangeUser()
12

{
13
&nbs p; //
14
&nbs p; // TODO: 在此处添加构造函数逻辑
15
&nbs p; //
16
}
17
public static WindowsIdentity CreateIdentity(string User, string Domain, string Password)
18
{
19
&nbs p; // The Windows NT user token.
20
; IntPtr tokenHandle = new IntPtr(0);
21
22
&nbs p; const int LOGON32_PROVIDER_DEFAULT = 0;
23
&nbs p; const int LOGON32_LOGON_NETWORK = 3;
24
25
&nbs p; tokenHandle = IntPtr.Zero;
26
27
&nbs p; // Call LogonUser to obtain a h andle to an access token.
28
; bool returnValue = LogonUser(User, Domain, Password,
29
&nbs p; LOGON32_LOGON_NETWORK, LO GON32_PROVIDER_DEFAULT,
30
&nbs p; ref tokenHandle);
31
32
&nbs p; if (false == returnValue)
33
&nbs p;
{
34
&nbs p; int ret = Marshal.GetLastWin32Error();
35
&nbs p; throw new Exception("LogonUser failed with error code: " + ret);
36
&nbs p; }
37
38
&nbs p; //The WindowsIdentity class makes a new copy of the token.
39
&nbs p; //It also handles calling CloseHandle&nbs p;for the copy.
40
; WindowsIdentity id = new WindowsIdentity(tokenHandle);
41
&nbs p;
42
&nbs p; return id;
43
}
44
45
[DllImport("advapi32.dll", SetLastError=true)]
46
private static extern bool LogonUser (String lpszUsername, String lpszDomain, String& nbsp;lpszPassword,
47
&nbs p; int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
48
49
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
50
private extern static bool CloseHandle(IntPtr handle);
51
52
}
53
}
54
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
