?
Solved

I want the code do actions as another user

Posted on 2007-12-05
3
Medium Priority
?
209 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 2000 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

Learn by Doing. Anytime. Anywhere.

Do you like to learn by doing?
Our labs and exercises give you the chance to do just that: Learn by performing actions on real environments.

Hands-on, scenario-based labs give you experience on real environments provided by us so you don't have to worry about breaking anything.

Question has a verified solution.

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

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Suggested Courses

771 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