[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

programmatic impersonation for file.Move

Posted on 2008-01-29
8
Medium Priority
?
1,136 Views
Last Modified: 2013-11-07
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.
0
Comment
Question by:acdagirl
  • 4
  • 4
8 Comments
 
LVL 11

Expert Comment

by:AkisC
ID: 20776339
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

0
 
LVL 11

Expert Comment

by:AkisC
ID: 20776349
The code works on Windows Forms (I tested)
I guess with a little handling -or- not, will fit in asp.net
0
 

Author Comment

by:acdagirl
ID: 20776725
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.
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 

Author Comment

by:acdagirl
ID: 20787960
anyone?
0
 
LVL 11

Accepted Solution

by:
AkisC earned 2000 total points
ID: 20803819
 Dim myDomainName As String = "yourDomain", thisUserName As String = "administator", thisPassword As String = "adminPass"
        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

     Dim vFile As String = "c:\myFile.txt"
     System.IO.File.Move(vFile, "c:\myDir\myMovedFile.txt")

            imp.ImpersonateStop()
        Catch ex As Exception 'make sure impersonation is stopped whether code succeeds or not
            MsgBox(ex.Message)
            imp.ImpersonateStop()
        End Try
0
 

Author Comment

by:acdagirl
ID: 20814530
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!
0
 
LVL 11

Expert Comment

by:AkisC
ID: 20814635
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...
0
 

Author Comment

by:acdagirl
ID: 20814858
thanks!
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
There may be issues when you are trying to access Outlook or send & receive emails or due to Outlook crash which leads to corrupt or damaged PST file. To eliminate the corruption from your PST file, you need to repair the corrupt Outlook PST file. U…
The video will let you know the exact process to import OST/PST files to the cloud based Office 365 mailboxes. Using Kernel Import PST to Office 365 tool, one can quickly import numerous OST/PST files to Office 365. Besides this, the tool also comes…
Suggested Courses

640 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question