0
我正在使用以下代碼來實現特定Windows帳戶的模擬,這是失敗。請幫助。Windows模擬失敗
using System.Security.Principal;
using System.Runtime.InteropServices;
public partial class Source_AddNewProduct : System.Web.UI.Page
{
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(
string principal,
string authority,
string password,
LogonSessionType logonType,
LogonProvider logonProvider,
out IntPtr token);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
enum LogonSessionType : uint
{
Interactive = 2,
Network,
Batch,
Service,
NetworkCleartext = 8,
NewCredentials
}
enum LogonProvider : uint
{
Default = 0, // default for platform (use this!)
WinNT35, // sends smoke signals to authority
WinNT40, // uses NTLM
WinNT50 // negotiates Kerb or NTLM
}
//impersonation is used when user tries to upload an image to a network drive
protected void btnPrimaryPicUpload_Click1(object sender, EventArgs e)
{
try
{
string mDocumentExt = string.Empty;
string mDocumentName = string.Empty;
HttpPostedFile mUserPostedFile = null;
HttpFileCollection mUploadedFiles = null;
string xmlPath = string.Empty;
FileStream fs = null;
StreamReader file;
string modify;
mUploadedFiles = HttpContext.Current.Request.Files;
mUserPostedFile = mUploadedFiles[0];
if (mUserPostedFile.ContentLength >= 0 && Path.GetFileName(mUserPostedFile.FileName) != "")
{
mDocumentName = Path.GetFileName(mUserPostedFile.FileName);
mDocumentExt = Path.GetExtension(mDocumentName);
mDocumentExt = mDocumentExt.ToLower();
if (mDocumentExt != ".jpg" && mDocumentExt != ".JPG" && mDocumentExt != ".gif" && mDocumentExt != ".GIF" && mDocumentExt != ".jpeg" && mDocumentExt != ".JPEG" && mDocumentExt != ".tiff" && mDocumentExt != ".TIFF" && mDocumentExt != ".png" && mDocumentExt != ".PNG" && mDocumentExt != ".raw" && mDocumentExt != ".RAW" && mDocumentExt != ".bmp" && mDocumentExt != ".BMP" && mDocumentExt != ".TIF" && mDocumentExt != ".tif")
{
Page.RegisterStartupScript("select", "<script language=" + Convert.ToChar(34) +
"VBScript" + Convert.ToChar(34) + "> MsgBox " + Convert.ToChar(34) + "Please upload valid picture file format" + Convert.ToChar(34) +
" , " + Convert.ToChar(34) + "64" + Convert.ToChar(34) + " , " + Convert.ToChar(34) + "WFISware" + Convert.ToChar(34) + "</script>");
}
else
{
int intDocLen = mUserPostedFile.ContentLength;
byte[] imageBytes = new byte[intDocLen];
mUserPostedFile.InputStream.Read(imageBytes, 0, mUserPostedFile.ContentLength);
//xmlPath = @ConfigurationManager.AppSettings["ImagePath"].ToString();
xmlPath = Server.MapPath("./../ProductImages/");
mDocumentName = Guid.NewGuid().ToString().Replace("-", "") + System.IO.Path.GetExtension(mUserPostedFile.FileName);
//if (System.IO.Path.GetExtension(mUserPostedFile.FileName) == ".jpg")
//{
//}
//if (System.IO.Path.GetExtension(mUserPostedFile.FileName) == ".gif")
//{
//}
mUserPostedFile.SaveAs(xmlPath + mDocumentName);
//Remove commenting till upto stmt xmlPath = "./../ProductImages/"; to implement impersonation
byte[] bytContent;
IntPtr token = IntPtr.Zero;
WindowsImpersonationContext impersonatedUser = null;
try
{
// Note: Credentials should be encrypted in configuration file
bool result = LogonUser(ConfigurationManager.AppSettings["ServiceAccount"].ToString(), "ad-ent",
ConfigurationManager.AppSettings["ServiceAccountPassword"].ToString(),
LogonSessionType.Network,
LogonProvider.Default,
out token);
if (result)
{
WindowsIdentity id = new WindowsIdentity(token);
// Begin impersonation
impersonatedUser = id.Impersonate();
mUserPostedFile.SaveAs(xmlPath + mDocumentName);
}
else
{
throw new Exception("Identity impersonation has failed.");
}
}
catch
{
throw;
}
finally
{
// Stop impersonation and revert to the process identity
if (impersonatedUser != null)
impersonatedUser.Undo();
// Free the token
if (token != IntPtr.Zero)
CloseHandle(token);
}
xmlPath = "./../ProductImages/";
xmlPath = xmlPath + mDocumentName;
string o_image = xmlPath; //For impersoantion uncomment this line and comment next line
//string o_image = "../ProductImages/" + mDocumentName;
ViewState["masterImage"] = o_image;
//fs = new FileStream(xmlPath, FileMode.Open, FileAccess.Read);
//file = new StreamReader(fs, Encoding.UTF8);
//modify = file.ReadToEnd();
//file.Close();
//commented by saurabh kumar 28may'09
imgImage.Visible = true;
imgImage.ImageUrl = ViewState["masterImage"].ToString();
img_Label1.Visible = false;
}
//e.Values["TemplateContent"] = modify;
//e.Values["TemplateName"] = mDocumentName.Replace(".xml", "");
}
}
catch (Exception ex)
{
ExceptionUtil.UI(ex);
Response.Redirect("errorpage.aspx");
}
}
}
執行時的代碼拋出system.invalidoperation異常。我已經完全控制目標文件夾到我正在模擬的windows服務帳戶。
知道WHERE拋出的異常是有用的...... – 2009-12-24 18:32:45
什麼行代碼會導致此異常? – Jim 2009-12-24 18:34:00
代碼的流程在以下循環中成功執行: if(result) {0} {0} WindowsIdentity id = new WindowsIdentity(token); //開始模仿 impersonatedUser = id.Impersonate(); mUserPostedFile.SaveAs(xmlPath + mDocumentName); } 即; if子句爲真,然後它引發異常。 – user238316 2009-12-25 12:23:09