473,802 Members | 2,446 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with Impersonation code please

I found this code on the MSDN site, from a post thats about a year old.
It does seem to work. However, I'm confused in how to use the impersonated
user.
I'd like to use impersonatedUse r to run some SQL commands. Any idea how I
would do this?
Thanks
Vayse

'************** *************** *************** *************** **************
Imports System
Imports System.Runtime. InteropServices
Imports System.Security .Principal
Imports System.Security .Permissions

Public Class LoginForm

Protected Friend canceled As Boolean = False

Friend Impersonating As Boolean = False

Private Sub btnOK_Click(ByV al sender As System.Object, ByVal e As
System.EventArg s) Handles btnOK.Click

Me.btnOK.Enable d = False
Me.Cursor = Cursors.WaitCur sor

If Impersonate_Use r() Then
Me.txtInfo.Text = My.User.Name
MsgBox("Success !")
End If

Me.btnOK.Enable d = True
Me.Cursor = Cursors.Default

End Sub

Private Function Impersonate_Use r() As Boolean

Dim tbtnOKenHandle As New IntPtr(0)
Dim dupeTbtnOKenHan dle As New IntPtr(0)

Try
Dim userName, domainName As String

domainName = txtDomain.Text
userName = txtUserName.Tex t

Const LOGON32_PROVIDE R_DEFAULT As Integer = 0
'This parameter causes LogonUser to create a primary tbtnOKen.
Const LOGON32_LOGON_I NTERACTIVE As Integer = 2

tbtnOKenHandle = IntPtr.Zero

' Call LogonUser to obtain a handle to an access tbtnOKen.
Dim returnValue As Boolean = LogonUser(userN ame, domainName,
txtPassword.Tex t, LOGON32_LOGON_I NTERACTIVE, LOGON32_PROVIDE R_DEFAULT,
tbtnOKenHandle)

'Set the flag on the form to see if they are impersonating
Impersonating = returnValue

If returnValue = False Then
Dim ret As Integer = Marshal.GetLast Win32Error()
Throw New System.Componen tModel.Win32Exc eption(ret)
Impersonate_Use r = False
Else
' Check the identity.
Debug.Print("Be fore impersonation: " +
WindowsIdentity .GetCurrent().N ame)

' Use the tbtnOKen handle returned by LogonUser.
Dim newId As New WindowsIdentity (tbtnOKenHandle )
Dim impersonatedUse r As WindowsImperson ationContext =
newId.Impersona te()

' Check the identity.

Debug.Print("Af ter impersonation: " +
WindowsIdentity .GetCurrent().N ame)

' Free the tbtnOKens.
If Not System.IntPtr.o p_Equality(tbtn OKenHandle,
IntPtr.Zero) Then
CloseHandle(tbt nOKenHandle)
End If

Impersonate_Use r = True
End If

Catch ex As Exception
MessageBox.Show (("Exception occurred. " + ex.Message),
Application.Pro ductName, MessageBoxButto ns.OK, MessageBoxIcon. Error)
End Try
End Function

Private Sub Cancel_Click(By Val sender As System.Object, ByVal e As
System.EventArg s) Handles btnCancel.Click

canceled = True
Me.Close()

End Sub

Private Declare Auto Function LogonUser Lib "advapi32.d ll" (ByVal
lpszUsername As [String], _
ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
ByRef phTbtnOKen As IntPtr) As Boolean

<DllImport("ker nel32.dll")_
Public Shared Function FormatMessage(B yVal 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

Public Declare Auto Function CloseHandle Lib "kernel32.d ll" (ByVal
handle As IntPtr) As Boolean

Public Declare Auto Function DuplicateTbtnOK en Lib "advapi32.d ll" (ByVal
ExistingTbtnOKe nHandle As IntPtr, _
ByVal SECURITY_IMPERS ONATION_LEVEL As Integer, _
ByRef DuplicateTbtnOK enHandle As IntPtr) As Boolean
Private Sub LoginForm_Load( ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
Me.txtInfo.Text = My.User.Name
End Sub
End Class

Apr 27 '07 #1
0 901

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
4241
by: Jason80 | last post by:
First I wrote some _VBScript to get info from OS, and now I wrote some code in VB.Net, and I have a problem now. Look at this script in vbs List1.vbs: strComputer = "."
1
10014
by: Ripa Horatiu | last post by:
Does anyone knows how can I impersonate to another user (basically Administrator) for a piece of my code? I've tried the samples provided by MS but they didn't worked. -- Horatiu Ripa
13
3633
by: Siegfried Heintze | last post by:
I refered the engineer at my hosting service to http://support.microsoft.com/default.aspx?scid=kb;en-us;825738 where he tried to follow the directions there. He said there was no such file: Document settings\ServerName\ASPNET\Local settings\Temp I said it must be a typo, they meant to say c:\Documents And Settings\Server Name\ASPNET\Local settings\temp.
3
1578
by: Jake Smythe | last post by:
Hello, I have some code that impersonates a user upon launching of the application. We now have the need to run some command line items. The impersonation doesn't seem to pass to the commands being run. Is there a way to do this? Basically looking for a way do a runas on a command line through an application. Thanks in advance. Below is some sample code, where we need to impersonate an admin to run command line code. Private Sub test
27
6716
by: vipleo | last post by:
I am having some issues, when I try to launch another process using Process.Start(ProcessStartInfo psi) on win xp sp2 box (Other versions of xp have no issue). Here is the detail. Main app checks for updates on startup and if updates are available, it launches separate exe to copy files. Before launching new process(exe), I am impersonating admin user as main app is being launched by non-admin user.
2
5524
by: jeremiah johnson | last post by:
I have a .net DLL that I've created (based on someone's post in this group, sorry I've forgotten who) and I need a little help with making it work. I want to provide the same functionality as "runas /netonly" and I'm using LOGON32_LOGON_NEW_CREDENTIALS as I've read here many times. I'm trying to launch a MOM operator console that will connect to a management server in a different domain. I've verified that this works with runas...
1
3595
by: gnusmsa | last post by:
ASP.NET 2.0 (C#) application Using Windows authentication and impersonation Windows Server 2003 (IIS6) Server is a member server on a domain Logged into server as a domain user that is in the local Administrators group on the server Workstation is on the same domain Logged into the workstation as the same domain user, which is also in the local Administrators group on the workstation
0
958
coderthebarbarian
by: coderthebarbarian | last post by:
Using VB 2005. I've got to be able to connect to a server app in both a domain and a workgroup scenario using IIS. The domain code passes Windows Authentication. The workgroup code requires the user to enter their username and password. Checking "local impersonation" in the ASP.NET Configuration Settings lets the code for domain access to work, but not the workgroup. Unchecking "local impersonation" breaks the domain code. Anybody have code for...
1
3665
by: pallavsheth | last post by:
Hi team, Can i use impersonation in JAVASCRIPT? I have one UNC share drive and i am using c#.net impersonation to upload the document. Now to view the document, code is available at .js file and i think browser is not able to detect the impersonated user. Can anyone please answer me whether can i use impersonation in javascript or not?
0
9562
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10536
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10063
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7598
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6838
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5494
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4270
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2966
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.