Solved

I want the code do actions as another user

Posted on 2007-12-05
3
194 Views
Last Modified: 2013-11-26
To prevent accidental creation or deletetios of folders I restricted some rights to the users.
I want that the user could create a directory only via the application that I'm making.

How to do :  

IO.Directory.CreateDirectory("T:\temp\")

but in administrators rights.
Can I put somewere the user name and the password in the code to execute the code like it was the administrator?
0
Comment
Question by:cpx_Support
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 9

Expert Comment

by:sognoct
ID: 20410165
remember to set   _userName, _password, _domain

here it is a script that should help you



using System.Security.Principal;
using System.Runtime.InteropServices;


//the following code executed before you perform your task

if ( ! ImpersonationUtil.Impersonate( _userName, _password, _domain ) )

{
MessageBox.Show("Impersonation failed.");
return;
}

//Perform task as this user here...

//After your task, do this:
ImpersonationUtil.UnImpersonate();


Here is the code for the ImpersonationUtil class:

/// <summary>
/// Impersonate a windows logon.
/// </summary>
public class ImpersonationUtil {

/// <summary>
/// Impersonate given logon information.
/// </summary>
/// <param name="logon">Windows logon name.</param>
/// <param name="password">password</param>
/// <param name="domain">domain name</param>
/// <returns></returns>
public static bool Impersonate( string logon, string password, string
domain ) {
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;

if( LogonUser( logon, 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 ( null != impersonationContext ) return true;
}
}

return false;
}

/// <summary>
/// Unimpersonate.
/// </summary>
public static void UnImpersonate() {
impersonationContext.Undo();
}

[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
public static extern int LogonUser(
string lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken );

[DllImport("advapi32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Aut o,
SetLastError=true)]
public extern static int DuplicateToken(
IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken );

private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_LOGON_NETWORK_CLEARTEXT = 4;
private const int LOGON32_PROVIDER_DEFAULT = 0;
private static WindowsImpersonationContext impersonationContext;
}
0
 

Author Comment

by:cpx_Support
ID: 20410253
Could you translate to VB?
0
 
LVL 9

Accepted Solution

by:
sognoct earned 500 total points
ID: 20418789
Imports System
Imports System.Security.Principal
Imports System.Security.Permissions
Imports System.Runtime.InteropServices

Public Class clsIMP

  <DllImport("advapi32.dll")> _
  Private Shared Function LogonUser(ByVal lpszUsername As String, _
                             ByVal lpszDomain As String, _
                             ByVal lpszPassword As String, _
                             ByVal dwLogonType As Integer, _
                             ByVal dwLogonProvider As Integer, _
                             ByRef phToken As Integer) As Boolean
  End Function


  <DllImport("Kernel32.dll")> _
  Private Shared Function GetLastError() As Integer
  End Function

  Private Enum Logon
    Interactive = 2
    Network = 3
    Batch = 4
    Service = 5
    Unlock = 7
    NetworkCleartext = 8
    NewCredentials = 9
  End Enum

  Private Enum Provider
    UserDefault = 0
    WindowsNT35 = 1
    WindowsNT40 = 2
    Windows2000 = 3
  End Enum

  Private NewContext As WindowsImpersonationContext

  <SecurityPermission(SecurityAction.Demand, ControlPrincipal:=True, UnmanagedCode:=True)> _
  Private Shared Function GetWindowsIdentity(ByVal Username As String, _
                                      ByVal Domain As String, _
                                      ByVal Password As String) As WindowsIdentity
    Dim SecurityToken As Integer
    Dim Success As Boolean

    'possible to extend program to allow changes to the logon type and provider
    'as Ineractive is slower and caches the information compared to the Logon.Network type.
    'Though that leaves open the private enumeration information.
    Success = LogonUser(Username, Domain, Password, _
                        Logon.Network, Provider.UserDefault, _
                        SecurityToken)

    If Not Success Then
      Throw New System.Exception("Logon Failed. Error: " & GetLastError())
      Err.Clear()
    Else
      GetWindowsIdentity = New WindowsIdentity(New IntPtr(SecurityToken))
    End If
  End Function

  Public Function ImpersonateUser(ByVal username As String, _
                  ByVal domain As String, ByVal pwd As String) As Boolean
    Dim NewIdentity As WindowsIdentity
    Dim CurIdentity As WindowsIdentity

    Try
      NewIdentity = GetWindowsIdentity(username, domain, pwd)

      If Not NewIdentity Is Nothing Then
        NewContext = NewIdentity.Impersonate
        CurIdentity = WindowsIdentity.GetCurrent

        Debug.WriteLine("Impersonated ID: " & CurIdentity.Name) 'used for demo/example

        RemoveImpersonation()

        'just removing impersonation for demo/example
        'would comment out for actual use and call the
        'the RemoveImpersonation() method if all went well
        'else it gets called upon error event

        CurIdentity = WindowsIdentity.GetCurrent 'used for demo/example
        Debug.WriteLine("Logon ID: " & CurIdentity.Name) 'used for demo/example

        ImpersonateUser = True
      Else
        Err.Raise(7000, ImpersonateUser)
      End If

    Catch ex As Exception
      'during any error be sure to remove any implimented impersonation
      'failure to do so, could leave computer/program still executing code
      'under guise of higher authority, possible for exploitation.
      RemoveImpersonation()
      ImpersonateUser = False
      Throw New System.Exception("IM Error: " & ex.Message)
      Err.Clear()
    End Try

    Return ImpersonateUser
  End Function

  'NOTE: Be sure to call this function as soon as you've completed whatever
  'task needing impersonation is completed. As leaving your program running
  'under higher authority is vunerable to exploitation from malious users.
  Public Function RemoveImpersonation() As Boolean
    Try
      If Not NewContext Is Nothing Then 'test if object was ever created/referenced
        NewContext.Undo() 'if so, then undo impersonation.
        RemoveImpersonation = True
      Else
        RemoveImpersonation = True 'never created object, so no impersonation to revert.
      End If
    Catch ex As Exception 'something happened during removal, so warn calling app to handle
      RemoveImpersonation = False
      Throw New System.Exception("Removal Failure: " & ex.Message)
      Err.Clear()
    End Try
    Return RemoveImpersonation
  End Function

End Class
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
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…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

739 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