473,657 Members | 2,693 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

impersonate user in windows forms

RTT
i'm writing a windows form but codebased a iwant to run the code as a
different user.

like in a webapplication you can impersonate a user so the website does not
run on the standard ASP.NET user.

is it possible to do the same for a windows form and define a user codebased
and run the code like that user is running the application.
Nov 21 '05 #1
8 17142
The following example demonstrates how to impersonate a user and then
revert
to the original identity.
[Visual Basic]
Imports System
Imports System.Runtime. InteropServices
Imports System.Security .Principal
Imports System.Security .Permissions

<Assembly:Secur ityPermissionAt tribute(Securit yAction.Request Minimum,
UnmanagedCode := true)>
Public Class Impersonation

<DllImport("C:\ \WINNT\\System3 2\\advapi32.dll ")> _
Public Shared Function LogonUser(lpszU sername As String, lpszDomain As
String, lpszPassword As String, _
dwLogonType As Integer, dwLogonProvider As Integer, ByRef
phToken As Integer) As Boolean
End Function

<DllImport("C:\ \WINNT\\System3 2\\Kernel32.dll ")> _
Public Shared Function GetLastError() As Integer
End Function

Public Shared Sub Main(args() As String)

'The Windows NT user token.
Dim token1 As Integer

'Get the user token for the specified user, machine, and password
using the unmanaged LogonUser method.

'The parameters for LogonUser are the user name, computer name,
password,
'Logon type (LOGON32_LOGON_ NETWORK_CLEARTE XT), Logon provider
(LOGON32_PROVID ER_DEFAULT),
'and user token.
Dim loggedOn As Boolean = LogonUser("bob" , "AARDVARK", "coffee", 3, 0,
token1)
Console.WriteLi ne("LogonUser called")

'Call GetLastError to try to determine why logon failed if it did not
succeed.
Dim ret As Integer = GetLastError()

Console.WriteLi ne("LogonUser Success? " + loggedOn)
Console.WriteLi ne("NT Token Value: " + token1)
If ret <> 0 Then
Console.WriteLi ne("Error code (126 == ""Specified module could not
be found""): " + ret)
End If

'Starting impersonation here:
Console.WriteLi ne("Before impersonation:" )
Dim mWI1 As WindowsIdentity = WindowsIdentity .GetCurrent()
Console.WriteLi ne(mWI1.Name)
Console.WriteLi ne(mWI1.Token)

Dim token2 As IntPtr = new IntPtr(token1)

Console.WriteLi ne("New identity created:")
Dim mWI2 As WindowsIdentity = new WindowsIdentity (token2)
Console.WriteLi ne(mWI2.Name)
Console.WriteLi ne(mWI2.Token)

'Impersonate the user.
Dim mWIC As WindowsImperson ationContext = mWI2.Impersonat e()

Console.WriteLi ne("After impersonation:" )
Dim mWI3 As WindowsIdentity = WindowsIdentity .GetCurrent()
Console.WriteLi ne(mWI3.Name)
Console.WriteLi ne(mWI3.Token)

'Revert to previous identity.
mWIC.Undo()

Console.WriteLi ne("After impersonation is reverted:")
Dim mWI4 As WindowsIdentity = WindowsIdentity .GetCurrent()
Console.WriteLi ne(mWI4.Name)
Console.WriteLi ne(mWI4.Token)
End Sub
End Class

"RTT" <RT*@pandora.be > wrote in message news:RT*@pandor a.be:
i'm writing a windows form but codebased a iwant to run the code as a
different user.

like in a webapplication you can impersonate a user so the website does
not
run on the standard ASP.NET user.

is it possible to do the same for a windows form and define a user
codebased
and run the code like that user is running the application.


Nov 21 '05 #2
RTT
nice...

but he give the error that he can't find the specified modules... but when i
look they are in the folder specified...

<DllImport("C:\ \WINNT\system32 \\ADVAPI32.DLL" )>

but the file does exist. any ideas?

thxs in advance

"scorpion53 061" <sc************ @nospamhereyaho o.com> wrote in message
news:%2******** *******@TK2MSFT NGP10.phx.gbl.. .
The following example demonstrates how to impersonate a user and then
revert
to the original identity.
[Visual Basic]
Imports System
Imports System.Runtime. InteropServices
Imports System.Security .Principal
Imports System.Security .Permissions

<Assembly:Secur ityPermissionAt tribute(Securit yAction.Request Minimum,
UnmanagedCode := true)>
Public Class Impersonation

<DllImport("C:\ \WINNT\\System3 2\\advapi32.dll ")> _
Public Shared Function LogonUser(lpszU sername As String, lpszDomain As
String, lpszPassword As String, _
dwLogonType As Integer, dwLogonProvider As Integer, ByRef
phToken As Integer) As Boolean
End Function

<DllImport("C:\ \WINNT\\System3 2\\Kernel32.dll ")> _
Public Shared Function GetLastError() As Integer
End Function

Public Shared Sub Main(args() As String)

'The Windows NT user token.
Dim token1 As Integer

'Get the user token for the specified user, machine, and password
using the unmanaged LogonUser method.

'The parameters for LogonUser are the user name, computer name,
password,
'Logon type (LOGON32_LOGON_ NETWORK_CLEARTE XT), Logon provider
(LOGON32_PROVID ER_DEFAULT),
'and user token.
Dim loggedOn As Boolean = LogonUser("bob" , "AARDVARK", "coffee", 3, 0,
token1)
Console.WriteLi ne("LogonUser called")

'Call GetLastError to try to determine why logon failed if it did not
succeed.
Dim ret As Integer = GetLastError()

Console.WriteLi ne("LogonUser Success? " + loggedOn)
Console.WriteLi ne("NT Token Value: " + token1)
If ret <> 0 Then
Console.WriteLi ne("Error code (126 == ""Specified module could not
be found""): " + ret)
End If

'Starting impersonation here:
Console.WriteLi ne("Before impersonation:" )
Dim mWI1 As WindowsIdentity = WindowsIdentity .GetCurrent()
Console.WriteLi ne(mWI1.Name)
Console.WriteLi ne(mWI1.Token)

Dim token2 As IntPtr = new IntPtr(token1)

Console.WriteLi ne("New identity created:")
Dim mWI2 As WindowsIdentity = new WindowsIdentity (token2)
Console.WriteLi ne(mWI2.Name)
Console.WriteLi ne(mWI2.Token)

'Impersonate the user.
Dim mWIC As WindowsImperson ationContext = mWI2.Impersonat e()

Console.WriteLi ne("After impersonation:" )
Dim mWI3 As WindowsIdentity = WindowsIdentity .GetCurrent()
Console.WriteLi ne(mWI3.Name)
Console.WriteLi ne(mWI3.Token)

'Revert to previous identity.
mWIC.Undo()

Console.WriteLi ne("After impersonation is reverted:")
Dim mWI4 As WindowsIdentity = WindowsIdentity .GetCurrent()
Console.WriteLi ne(mWI4.Name)
Console.WriteLi ne(mWI4.Token)
End Sub
End Class

"RTT" <RT*@pandora.be > wrote in message news:RT*@pandor a.be:
i'm writing a windows form but codebased a iwant to run the code as a
different user.

like in a webapplication you can impersonate a user so the website does
not
run on the standard ASP.NET user.

is it possible to do the same for a windows form and define a user
codebased
and run the code like that user is running the application.

Nov 21 '05 #3
RTT,

Why do you not search for it?
Cor
Nov 21 '05 #4
RTT
what do you mean search?

the dll's are in de folder like specified in the code. but he can't load it.

search? other way to load?

sorry, first time working with dll's so much :s
"Cor Ligthert" <no************ @planet.nl> wrote in message
news:ef******** *****@tk2msftng p13.phx.gbl...
RTT,

Why do you not search for it?
Cor

Nov 21 '05 #5

I don't know what to tell you.

Maybe something is wrong with your computer?

"RTT" <RT*@pandora.be > wrote in message news:RT*@pandor a.be:
nice...

but he give the error that he can't find the specified modules... but when
i
look they are in the folder specified...

<DllImport("C:\ \WINNT\system32 \\ADVAPI32.DLL" )>

but the file does exist. any ideas?

thxs in advance

"scorpion53 061" <sc************ @nospamhereyaho o.com> wrote in message
news:%2******** *******@TK2MSFT NGP10.phx.gbl.. .
The following example demonstrates how to impersonate a user and then
revert
to the original identity.
[Visual Basic]
Imports System
Imports System.Runtime. InteropServices
Imports System.Security .Principal
Imports System.Security .Permissions

<Assembly:Secur ityPermissionAt tribute(Securit yAction.Request Minimum,
UnmanagedCode := true)>
Public Class Impersonation

<DllImport("C:\ \WINNT\\System3 2\\advapi32.dll ")> _
Public Shared Function LogonUser(lpszU sername As String, lpszDomain As
String, lpszPassword As String, _
dwLogonType As Integer, dwLogonProvider As Integer, ByRef
phToken As Integer) As Boolean
End Function

<DllImport("C:\ \WINNT\\System3 2\\Kernel32.dll ")> _
Public Shared Function GetLastError() As Integer
End Function

Public Shared Sub Main(args() As String)

'The Windows NT user token.
Dim token1 As Integer

'Get the user token for the specified user, machine, and password
using the unmanaged LogonUser method.

'The parameters for LogonUser are the user name, computer name,
password,
'Logon type (LOGON32_LOGON_ NETWORK_CLEARTE XT), Logon provider
(LOGON32_PROVID ER_DEFAULT),
'and user token.
Dim loggedOn As Boolean = LogonUser("bob" , "AARDVARK", "coffee", 3, 0,
token1)
Console.WriteLi ne("LogonUser called")

'Call GetLastError to try to determine why logon failed if it did not
succeed.
Dim ret As Integer = GetLastError()

Console.WriteLi ne("LogonUser Success? " + loggedOn)
Console.WriteLi ne("NT Token Value: " + token1)
If ret <> 0 Then
Console.WriteLi ne("Error code (126 == ""Specified module could not
be found""): " + ret)
End If

'Starting impersonation here:
Console.WriteLi ne("Before impersonation:" )
Dim mWI1 As WindowsIdentity = WindowsIdentity .GetCurrent()
Console.WriteLi ne(mWI1.Name)
Console.WriteLi ne(mWI1.Token)

Dim token2 As IntPtr = new IntPtr(token1)

Console.WriteLi ne("New identity created:")
Dim mWI2 As WindowsIdentity = new WindowsIdentity (token2)
Console.WriteLi ne(mWI2.Name)
Console.WriteLi ne(mWI2.Token)

'Impersonate the user.
Dim mWIC As WindowsImperson ationContext = mWI2.Impersonat e()

Console.WriteLi ne("After impersonation:" )
Dim mWI3 As WindowsIdentity = WindowsIdentity .GetCurrent()
Console.WriteLi ne(mWI3.Name)
Console.WriteLi ne(mWI3.Token)

'Revert to previous identity.
mWIC.Undo()

Console.WriteLi ne("After impersonation is reverted:")
Dim mWI4 As WindowsIdentity = WindowsIdentity .GetCurrent()
Console.WriteLi ne(mWI4.Name)
Console.WriteLi ne(mWI4.Token)
End Sub
End Class

"RTT" <RT*@pandora.be > wrote in message news:RT*@pandor a.be:
i'm writing a windows form but codebased a iwant to run the code as
a
different user.

like in a webapplication you can impersonate a user so the website
does
not
run on the standard ASP.NET user.

is it possible to do the same for a windows form and define a user
codebased
and run the code like that user is running the application.


Nov 21 '05 #6
"RTT" <RT*@pandora.be > schrieb:
but he give the error that he can't find the specified modules... but when
i
look they are in the folder specified...

<DllImport("C:\ \WINNT\system32 \\ADVAPI32.DLL" )>

but the file does exist. any ideas?


Simply specify the file name only ('<DllImport("A DVAPI32.DLL")>' ). Double
backslashes are /not/ required in VB.NET!

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #7
RTT,

Did you set a reference to the namespace in this page?

http://msdn.microsoft.com/library/de...classtopic.asp

I hope this helps,

Cor
Nov 21 '05 #8
RTT,

Did you set a reference to the namespace in this page?

http://msdn.microsoft.com/library/de...classtopic.asp

(I don't know if I linked the message to the right question)

I hope this helps,

Cor

Nov 21 '05 #9

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

Similar topics

2
3754
by: Greg Bacchus | last post by:
Hi, I'm getting an exception that really has me stumped. It's sporadic at best, it's only happened a handful of times. This particular time it happened when the user pressed 'Alt-S' to save the data that they were entering. Following is all exception information. Any thoughts much appreciated. Cheers
0
2308
by: Tim Haughton | last post by:
I've just released an article on using Test Driven Development with C# and Windows Forms. GUI's are often difficult to test, so I thought it might be of interest. The article along with the example source code can be downloaded here: http://www.blogitek.com/timhaughton/archives/files/User%20Interrogator%20And%20TDD.zip The article text is below. Not sure what it will do to the formatting when
15
3861
by: Wiktor Zychla | last post by:
today we've found a critical issue regarding the ListView from Windows.Forms. it was confirmed on several machines with Win2K and XP. here's the problem: create a ListView with about 50000 rows. now use task manager to see the GDI usage of the process. everything seems normal. now catch the ListView's scroller and start to move it downwards. you have to hold the constant speed so that the ListView is constantly repainted. look at the...
3
2497
by: Chris Dunaway | last post by:
A quick scan of the group did not immediately reveal an answer to my questions so here goes. First let me describe my app and then I'll ask the questions. I am writing a Windows Forms App (not Web Forms) that serves as a thin client to some web services. In other words, the Windows Forms app will be installed on the client machines and that app will call web services that are deployed on my server.
6
3090
by: richi | last post by:
Hi... Okay this is driving me mad. I have a very simple webpage served up from my webserver which uses the following code to populate 3 labels. lblOne.Text = Page.User.Identity.Name lblTwo.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name lblThree.Text = System.Threading.Thread.CurrentPrincipal.Identity.Name In my web.config file I have :-
4
3519
by: James | last post by:
I have a VB windows forms application that accesses a Microsoft Access database that has been secured using user-level security. The application is being deployed using No-Touch deployment. The objective in utilizing this new deployment method is to reduce the maintenance overhead as well as making it easier for my users to setup and run the application initially. I have VS 2002, Windows XP, Access XP(2000 format). He is my problem....
0
3044
by: James | last post by:
I have a VB windows forms application that accesses a Microsoft Access database that has been secured using user-level security. The application is being deployed using No-Touch deployment. The objective in utilizing this new deployment method is to reduce the maintenance overhead as well as making it easier for my users to setup and run the application initially. I have VS 2002, Windows XP, Access XP(2000 format). He is my problem....
1
3504
by: Michael Howes | last post by:
I would think this would be very, very easy but in the 50 searches I've done I haven't found anything. If our application requires login and that user/password be a local windows account or more detailed, a user that has been added to the Power Users group that is either a local account or a active directory account how do I authenticate? I've found code that seems to do this against Active Directory
21
3338
by: Dan Tallent | last post by:
In my application I have a form (Customer) that I want to be able to open multiple copies at once. Within this form I have other forms that can be opened. Example: ZipCode. When the user enters a zipcode that is unknown this form will open. I don't want users to modify any of this customers data until they close the zipcode form. Normally this can accomplished using a modal form, however this prevents me from opening a new copy of...
9
1796
by: Scott Stark | last post by:
Hello, I'm *just* delving into Windows forms-based programming without the benefit of any books, etc. I have a background in light ASP.NET work, so forgive me if this is a really basic question related to Windows GUI. I've created a "Form1.vb" file in my project, added a menustrip, etc. When a user clicks on a menu item, how do I get it to show a new form in the same window?
0
8403
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8316
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
8833
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
8737
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8509
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6174
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
5636
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
4168
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...
2
1967
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.