Link to home
Start Free TrialLog in
Avatar of acdagirl
acdagirl

asked on

programmatic impersonation for file.Move

I have some old impersonation code that is supposed to let me access a remote fileshare. I'm trying to add a file.Move within the code somewhere but it keeps failing without giving me real details on the error. The fileshare is maintained by another IT department and so I can't modify users/security on that box myself, hence the programmatic part. does anyone know a good article or tutorial on how to move files from a local box to a remote one using impersonation? I'm using asp.net as this is a web app.
Avatar of AkisC
AkisC
Flag of Greece image

Try this
        Dim myDomainName As String = "", thisUserName As String = "", thisPassword As String = ""
        Dim imp As New RunAs_Impersonator
        Try
            imp.ImpersonateStart(myDomainName, thisUserName, thisPassword) 'creates new context using token for user
            '//Add code to run as UserName here
            'everything between ImpersonateStart and ImpersonateStop will be run as the impersonated user
            imp.ImpersonateStop()
        Catch ex As Exception 'make sure impersonation is stopped whether code succeeds or not
            MsgBox(ex.Message)
            imp.ImpersonateStop()
        End Try
Imports System
Imports System.Runtime.InteropServices
Imports System.Security.Principal
Imports System.Security.Permissions
Imports Microsoft.VisualBasic
<Assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode:=True), _
 Assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name:="FullTrust")> 
 
Public Class RunAs_Impersonator
#Region "Private Variables and Enum Constants"
    Private tokenHandle As New IntPtr(0)
    Private dupeTokenHandle As New IntPtr(0)
    Private impersonatedUser As WindowsImpersonationContext
#End Region
#Region "Properties"
 
#End Region
#Region "Public Methods"
    Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean
 
    Public Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, _
      ByVal SECURITY_IMPERSONATION_LEVEL As Integer, _
      ByRef DuplicateTokenHandle As IntPtr) As Boolean
 
    ' Test harness.
    ' If you incorporate this code into a DLL, be sure to demand FullTrust.
    <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
    Public Sub ImpersonateStart(ByVal Domain As String, ByVal userName As String, ByVal Password As String)
        Try
            tokenHandle = IntPtr.Zero
            ' Call LogonUser to obtain a handle to an access token.
            Dim returnValue As Boolean = LogonUser(userName, Domain, Password, 2, 0, tokenHandle)
 
            'check if logon successful
            If returnValue = False Then
                Dim ret As Integer = Marshal.GetLastWin32Error()
                Console.WriteLine("LogonUser failed with error code : {0}", ret)
                Throw New System.ComponentModel.Win32Exception(ret)
                Exit Sub
            End If
 
            'Logon succeeded
 
            ' Use the token handle returned by LogonUser.
            Dim newId As New WindowsIdentity(tokenHandle)
            impersonatedUser = newId.Impersonate()
        Catch ex As Exception
            Throw ex
            Exit Sub
        End Try
        MsgBox("running as " & impersonatedUser.ToString & " -- " & WindowsIdentity.GetCurrent.Name)
    End Sub
    <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
    Public Sub ImpersonateStop()
        ' Stop impersonating the user.
        impersonatedUser.Undo()
 
        ' Free the tokens.
        If Not System.IntPtr.op_Equality(tokenHandle, IntPtr.Zero) Then
            CloseHandle(tokenHandle)
        End If
        MsgBox("running as " & Environment.UserName)
    End Sub
#End Region
#Region "Private Methods"
    Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
     ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
     ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
     ByRef phToken As IntPtr) As Boolean
 
    <DllImport("kernel32.dll")> _
    Public Shared Function FormatMessage(ByVal dwFlags As Integer, ByRef lpSource As IntPtr, _
     ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByRef lpBuffer As [String], _
     ByVal nSize As Integer, ByRef Arguments As IntPtr) As Integer
    End Function
#End Region
End Class

Open in new window

The code works on Windows Forms (I tested)
I guess with a little handling -or- not, will fit in asp.net
Avatar of acdagirl
acdagirl

ASKER

where is the file.move section? I already have the code you provided as explained above. I need the file moving code in there somewhere.
anyone?
ASKER CERTIFIED SOLUTION
Avatar of AkisC
AkisC
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks - it's what I wanted to check, however it seems that because i'm trying to move a file from a file control (not the standard .net file upload) I have additional complications with security - the control I'm using appears to buffer the file in a temp directory which then requires different authentication. I think I'm just going to have to copy the file locally/temporarily on the web server then move it to the file share using the impersonation code above.

thanks!
On the web server side the folder you want to move your file to must have IUSR rights to read/write/modify.
You should check with your ISP to allow this in the folder -or- if you run your web server check the folder

I am developing .asp pages, and I have not much of expirience in .aspx, but definately you must have IUSR rights to any folder to modify its contents

Have fun coding...
thanks!