2009-12-24 89 views
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服务帐户。

+0

知道WHERE抛出的异常是有用的...... – 2009-12-24 18:32:45

+0

什么行代码会导致此异常? – Jim 2009-12-24 18:34:00

+0

代码的流程在以下循环中成功执行: if(result) {0} {0} WindowsIdentity id = new WindowsIdentity(token); //开始模仿 impersonatedUser = id.Impersonate(); mUserPostedFile.SaveAs(xmlPath + mDocumentName); } 即; if子句为真,然后它引发异常。 – user238316 2009-12-25 12:23:09

回答

0

我无法理解你在尝试什么。但我可以说的是,只有当应用程序运行的帐户是管理员时,才能成功模拟任何用户。如果应用程序运行的帐户是非管理员使用的runas。如果您使用的是ASP.NET,请确保该网站在具有该网络共享管理权限的模拟管理员帐户下运行。