我认为您的方法正确,“访问被拒绝”的问题是由于 ASP.NET 进程与 ASPNET 用户一起运行,该用户具有有限的权限,这就是您遇到的错误。您可以做的是为您的 Web 应用程序设置 imersnation。您可以通过更改 web.config 或代码来实现。有关模拟的更多信息,您可以在此处阅读
web.comfig 非常简单,您需要在 web.config 的 system.web 部分添加以下行
<identity impersonate="true" userName="domain\user" password="password" />
用户需要在服务器上具有管理员权限
如果您想在下面的代码中执行模拟是如何执行此操作的示例:
...
WindowsImpersonationContext context = ImpersonateUser("domain", "user", "password");
// kill your process
context.Undo();
...
[DllImport("advapi32.dll")]
private static extern bool LogonUser(
String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("advapi32.dll")]
private static extern bool DuplicateToken(
IntPtr ExistingTokenHandle, int ImpersonationLevel,
ref IntPtr DuplicateTokenHandle);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
private enum SecurityImpersonationLevel
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
private enum LogonTypes
{
LOGON32_PROVIDER_DEFAULT=0,
LOGON32_LOGON_INTERACTIVE=2,
LOGON32_LOGON_NETWORK=3,
LOGON32_LOGON_BATCH=4,
LOGON32_LOGON_SERVICE=5,
LOGON32_LOGON_UNLOCK=7,
LOGON32_LOGON_NETWORK_CLEARTEXT=8,
LOGON32_LOGON_NEW_CREDENTIALS=9
}
public static WindowsImpersonationContext ImpersonateUser(string domain, string username, string password)
{
WindowsImpersonationContext result = null;
IntPtr existingTokenHandle = IntPtr.Zero;
IntPtr duplicateTokenHandle = IntPtr.Zero;
try
{
if (LogonUser(username, domain, password,
(int)LogonTypes.LOGON32_LOGON_NETWORK_CLEARTEXT, (int)LogonTypes.LOGON32_PROVIDER_DEFAULT,
ref existingTokenHandle))
{
if (DuplicateToken(existingTokenHandle,
(int)SecurityImpersonationLevel.SecurityImpersonation,
ref duplicateTokenHandle))
{
WindowsIdentity newId = new WindowsIdentity(duplicateTokenHandle);
result = newId.Impersonate();
}
}
}
finally
{
if (existingTokenHandle != IntPtr.Zero)
CloseHandle(existingTokenHandle);
if (duplicateTokenHandle != IntPtr.Zero)
CloseHandle(duplicateTokenHandle);
}
return result;
}
希望这会有所帮助,问候