阅读使用ASP.NET模拟远程文件 [英] Reading remote file using ASP.NET impersonation
问题描述
我想读取存储在远程服务器上的PDF文件。我已经提供了一个用户名/密码已读访问权。
I want to read a pdf stored on a remote server. I have been provided with a username/password which has read access rights.
我使用这个网址 https://support.microsoft.com/kb / 306158
我记录一切日志文件只是为了帮助调试。
I am logging everything to a logFile just to help with debugging.
StreamWriter sw = new StreamWriter(Server.MapPath("~/log/logFile.txt"), true);
sw.WriteLine("Just before Impersonation");
if(impersonateValidUser("username", "domain", "password"))
{
try
{
byte[] bytes = File.ReadAllBytes(documentName);
sw.WriteLine("Bytes read!!");
undoImpersonation();
}
catch(Exception ex)
{
sw.WriteLine(ex.Message + "\n" + ex.StackTrace);
return;
}
else
{
sw.WriteLine("Impersonation Failed");
return;
}
在我的日志文件,我只看到了就模拟之前。
无论是尝试,也不catch块的消息被写入日志文件。出人意料的是,我没有看到模仿失败的消息。
In my log file, I just see the "Just before Impersonation". Neither of the messages of the try nor catch block is written to the log file. Surprisingly, I do not see the impersonation failed message.
只是想知道如果任何人有这种行为的previous经验?是否有访问远程计算机上的文件中的任何额外的要求吗?我知道远程机器确实有ADVAPI32.DLL和KERNEL32.DLL
Just wondering if anyone has previous experience with this kind of behavior? Is there any extra requirement to access file on a remote machine? I know that the remote machine does have advapi32.dll and kernel32.dll
推荐答案
我们不得不使用MSDN样本,以及,如果我没有记错,它与把手越来越封闭prematurely做题。
We had problems using the MSDN sample as well and if I recall correctly, it had to do with handles getting closed prematurely.
我们结束了在下面的方式,这一直很适合我们改写:
We ended up rewriting it in the following way, which has worked very well for us:
private void DoLogin()
{
var token = LogonAsUser(userName, domain, password);
if (!IntPtr.Equals(token, IntPtr.Zero))
{
WindowsImpersonationContext impersonatedUser = null;
try
{
var newIdentity = new WindowsIdentity(token);
impersonatedUser = newIdentity.Impersonate();
// Do impersonated work here
}
finally
{
if (impersonatedUser != null)
{
impersonatedUser.Undo();
}
LogonAsUserEnd(token);
}
}
}
private IntPtr LogonAsUser(String userName, String domain, String password)
{
IntPtr token = IntPtr.Zero;
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
return token;
}
else
{
return IntPtr.Zero;
}
}
private void LogonAsUserEnd(IntPtr token) {
if (!IntPtr.Equals(token, IntPtr.Zero))
{
CloseHandle(token);
}
}
另外一个侧面说明:我们定义LogonUserA为返回一个布尔值,而不是一个int,它也可能是您所遇到的问题的一部分。
One other side note: we defined LogonUserA as returning a bool, not an int, which could also be part of the issue you are encountering.
这篇关于阅读使用ASP.NET模拟远程文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!