Impersonate user for file read/write on network share

I am having trouble getting the logon user function to work. I am attempting to access a share on a network computer.  The account I am using is a local account on the manchine - Not a domain account.  If I use the logon_new_credentials, the login succeeds but the createdirectory returns bad user/password



IntPtr lnToken;
       
     //   LOGON32_LOGON_NEW_CREDENTIALS - Using this the logon succeeds but the create directory still returns bad username/ passord
        int TResult = LogonUser(@"remotecomputer\adminuser", "RemoteComputer", "password", LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out lnToken);
        Win32Exception e = new Win32Exception();
        string x =e.Message;
        if ( TResult > 0 )
            {
 
           ImpersonateLoggedOnUser(lnToken);
           using( WindowsIdentity.Impersonate(lnToken))
           {

               Directory.CreateDirectory("\\\\remotecomputer\\ShareedFolder\\Test");

           }
           
                  StringBuilder sb = new StringBuilder(80,80);
                  RevertToSelf();
                  CloseHandle(lnToken);
            }
            else
            {
                  
            }


            return;
LVL 9
JonMnyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

topdog770Commented:
The code is not very clean, I'm on my out of the office but for what it's worth...

I liberally borrowed from:

http://www.eggheadcafe.com/community/aspnet/2/28798/logonusera-impersonation.aspx 
and
http://support.microsoft.com/?scid=306158
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
 
using System.Security;
using System.Security.Principal;
using System.Runtime;
using System.Runtime.InteropServices;
 
using System.Web;
using System.Web.Security;
 
namespace Impersonate
{
    class Program
    {
        [System.Runtime.InteropServices.DllImport( "advapi32.dll" )]
        public static extern int LogonUser(String lpszUserName,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);
 
        [DllImport( "advapi32.dll", CharSet = CharSet.Auto, SetLastError = true )]
        public static extern int DuplicateToken(IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);
 
        [DllImport( "advapi32.dll", CharSet = CharSet.Auto, SetLastError = true )]
        public static extern bool RevertToSelf();
 
        [DllImport( "kernel32.dll", CharSet = CharSet.Auto )]
        public static extern bool CloseHandle(IntPtr handle);
 
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_LOGON_INTERACTIVE = 2;
 
        static WindowsImpersonationContext wic;         
 
        static void Main(string[] args)
        {
            IntPtr lnToken;
            
             if( ImpersonateValidUser( "michaell", "cmp-0641", "wilma"))
            {
                using (wic)
               { 
               
               string dir = @"\\cmp-0641\C$\" + "Test";
                System.IO.Directory.CreateDirectory( dir );
               } 
          
                StringBuilder sb = new StringBuilder( 80, 80 );
                RevertToSelf( );
                //CloseHandle( lnToken );
            }
            else
            {
 
            }
            return;        
        }
 
        static public bool ImpersonateValidUser(String userName, String domain, String password)
        {
            WindowsIdentity wi;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;
 
            if (RevertToSelf( ))
            {
                if (LogonUser( userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token ) != 0)
                {
                    if (DuplicateToken( token, 2, ref tokenDuplicate ) != 0)
                    {
                        wi = new WindowsIdentity( tokenDuplicate );
                        wic = wi.Impersonate( );
                        if (wic != null)
                        {
                            CloseHandle( token );
                            CloseHandle( tokenDuplicate );
                            return true;
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
                CloseHandle( token );
            if (tokenDuplicate != IntPtr.Zero)
                CloseHandle( tokenDuplicate );
            return false;
        }
 
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.