<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>crunchlife: Temporary Identity Impersonation in ASP.NET</title>
    <link>http://crunchlife.com/articles/2008/05/27/temporary-identity-impersonation-in-asp-net</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description></description>
    <item>
      <title>Temporary Identity Impersonation in ASP.NET</title>
      <description>&lt;p&gt;Uploading files in an ASP.NET application is relatively easy to do. Uploading to a remote machine is a little bit trickier, but certainly doable. I followed a &lt;a href="http://aspalliance.com/336_Upload_Files_Using_ASPNET_Impersonation_and_UNC_Share.all" target="_blank"&gt;set of instructions&lt;/a&gt; on aspalliance.com, but rather than declare an account to impersonate in my web.config file, I decided to do it in code. That way I could use impersonation only when needed and encapsulate it for later use.&lt;/p&gt;

&lt;p&gt;I referred to an &lt;a href="http://support.microsoft.com/kb/306158#4" target="_blank"&gt;article&lt;/a&gt; on Microsoft&amp;#8217;s Help and Support website about how to implement impersonation. Their code worked great, but I decided to put it in a class to help keep things &lt;a href="http://en.wikipedia.org/wiki/DRY" target="_blank"&gt;DRY&lt;/a&gt;.&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;using System;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Runtime.InteropServices;

namespace Utilities
{    
    public class ImpersonateUser
    {
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;

        WindowsImpersonationContext impersonationContext;

        [DllImport(&amp;quot;advapi32.dll&amp;quot;)]
        public static extern int LogonUserA(String lpszUserName,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);
        [DllImport(&amp;quot;advapi32.dll&amp;quot;, CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int DuplicateToken(IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);

        [DllImport(&amp;quot;advapi32.dll&amp;quot;, CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool RevertToSelf();

        [DllImport(&amp;quot;kernel32.dll&amp;quot;, CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);

        public bool ImpersonateValidUser(String userName, String domain, String password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
                CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero)
                CloseHandle(tokenDuplicate);
            return false;
        }

        public void UndoImpersonation()
        {
            impersonationContext.Undo();
        }
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;After referencing my Utilities namespace I was then able to impersonate the account required for uploading:&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;if (FileUpload1.HasFile)
{
    ImpersonateUser impersonateUser = new ImpersonateUser();

    if (impersonateUser.ImpersonateValidUser(&amp;quot;userName&amp;quot;, &amp;quot;&amp;quot;, &amp;quot;password&amp;quot;))
    {
        FileUpload1.SaveAs(Server.MapPath(&amp;quot;~/files/fileName.txt&amp;quot;));
        impersonateUser.UndoImpersonation();
    }
    else
    {
        throw new Exception(&amp;quot;Identity impersonation has failed.&amp;quot;);
    }   
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;*The SaveAs method of the FileUpload control requires a root path. Using Server.MapPath will provide the root path of your IIS virtual folder.&lt;/strong&gt;&lt;/p&gt;</description>
      <pubDate>Tue, 27 May 2008 09:01:00 -0700</pubDate>
      <guid isPermaLink="false">urn:uuid:9aea73ef-a3d1-4208-9128-12eb032da707</guid>
      <author>Ryan Baxter</author>
      <link>http://crunchlife.com/articles/2008/05/27/temporary-identity-impersonation-in-asp-net</link>
      <category>Code Snippets</category>
      <category>ASPNET</category>
      <category>dotNET</category>
      <enclosure type="image/jpeg" length="60658" url="http://crunchlife.com/files/lock.jpg"/>
      <trackback:ping>http://crunchlife.com/articles/trackback/66</trackback:ping>
    </item>
    <item>
      <title>"Temporary Identity Impersonation in ASP.NET" by Al</title>
      <description>This is awesome!!!
You are the man!</description>
      <pubDate>Wed, 02 Mar 2011 08:16:34 -0800</pubDate>
      <guid isPermaLink="false">urn:uuid:7d95bd24-6753-460a-8623-e016d2230e43</guid>
      <link>http://crunchlife.com/articles/2008/05/27/temporary-identity-impersonation-in-asp-net#comment-145548</link>
    </item>
    <item>
      <title>"Temporary Identity Impersonation in ASP.NET" by Ryan Baxter</title>
      <description>Awesome!  Glad to help.</description>
      <pubDate>Mon, 07 Sep 2009 07:26:49 -0700</pubDate>
      <guid isPermaLink="false">urn:uuid:bbb02075-d8fc-45c6-aa83-2445347fd80d</guid>
      <link>http://crunchlife.com/articles/2008/05/27/temporary-identity-impersonation-in-asp-net#comment-29036</link>
    </item>
    <item>
      <title>"Temporary Identity Impersonation in ASP.NET" by Joe</title>
      <description>You saved my life!</description>
      <pubDate>Mon, 07 Sep 2009 07:24:22 -0700</pubDate>
      <guid isPermaLink="false">urn:uuid:e4d0ce52-3696-4d56-9792-3c41d85ea75c</guid>
      <link>http://crunchlife.com/articles/2008/05/27/temporary-identity-impersonation-in-asp-net#comment-29035</link>
    </item>
  </channel>
</rss>

