Windows Impersonation failed

Posted by skprocks on Stack Overflow See other posts from Stack Overflow or by skprocks
Published on 2009-12-24T17:36:38Z Indexed on 2010/05/20 8:10 UTC
Read the original article Hit count: 315

Filed under:
|

I am using following code to implement impersonation for the particular windows account,which is failing.Please help.

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");
        }


    }
}

The code on execution throws system.invalidoperation exception.I have provided full control to destination folder to the windows service account that i am impersonating.

© Stack Overflow or respective owner

Related posts about impersonation

Related posts about Windows