473,624 Members | 2,232 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

impersonation in web application

Hi
I made a naff web application which uses the impersonation method in MSDN
(can't find it now, but it basically revolves around creating a token by
calling the LogonUser API, calling DuplicateToken API on it, and then calling
w.Impersonate() where w is a System.Security .Principal.Wind owsIdentity
object). This is the only real point of the said web application if I'm
brutally honest with myself ;-) however it leaves me curious, as does any
test project!

I set up this web application, the idea of which being to shell commands on
the web server and see the output in a webforms text box, from a remote
machine.
I thought the impersonation worked because all the return values were as
expected, and what's more a totally independent Environment.Use rName function
returned the username I had impersonated. However, when I try to do
"dir "c:\documen ts and settings\bonj\* .txt" /b /s
from the web application, it returns 'file not found' but when I copy that
command into a DOS box (logged on as bonj) it returns a whole list of text
files. I'm suspicous that there's some permissions thing that windows is
hiding from me. What, though?

The code for the impersonation is this:

Public Class Impersonator
Implements IDisposable

Const LOGON32_LOGON_I NTERACTIVE As Int32 = 2
Const LOGON32_PROVIDE R_DEFAULT As Int32 = 0
Const SecurityImperso nation As Int32 = 2

Dim impersonationCo ntext As WindowsImperson ationContext

Declare Auto Function LogonUser Lib "advapi32.d ll" (ByVal lpszUserName
As String, _
ByVal lpszDomain As String, _
ByVal lpszPassword As String, _
ByVal dwLogonType As Int32, _
ByVal dwLogonProvider As Int32, _
ByRef phToken As IntPtr) As Int32
Declare Auto Function DuplicateToken Lib "advapi32.d ll" _
(ByVal ExistingTokenHa ndle As IntPtr, _
ByVal ImpersonationLe vel As Int32, _
ByRef DuplicateTokenH andle As IntPtr) As Int32

Public Function Impersonate(ByV al UserName As String, ByVal Domain As
String, ByVal Password As String) As Boolean

Dim tempWindowsIden tity As WindowsIdentity
Dim token As IntPtr
Dim tokenDuplicate As IntPtr

If LogonUser(UserN ame, Domain, password, LOGON32_LOGON_I NTERACTIVE, _
LOGON32_PROVIDE R_DEFAULT, token) <> 0 Then
If DuplicateToken( token, 2, tokenDuplicate) <> 0 Then
tempWindowsIden tity = New WindowsIdentity (tokenDuplicate )
impersonationCo ntext = tempWindowsIden tity.Impersonat e()
Return Not (impersonationC ontext Is Nothing)
End If
End If
End Function

Public Sub Dispose() Implements System.IDisposa ble.Dispose
If Not impersonationCo ntext Is Nothing Then
impersonationCo ntext.Undo()
End Sub
End Class
and the code for the cmdCommand click button on the web form is:

Private Sub cmdGo_Click(ByV al sender As System.Object, ByVal e As
System.EventArg s) Handles cmdGo.Click
txtResults.Text = ""
Dim p As New Process
Dim psi As New
ProcessStartInf o(Environment.G etEnvironmentVa riable("comspec "), _
"/c """ + txtCommand.Text + """")
psi.UseShellExe cute = False
psi.CreateNoWin dow = True
psi.RedirectSta ndardOutput = True
psi.RedirectSta ndardError = True
psi.WindowStyle = ProcessWindowSt yle.Hidden
p.StartInfo = psi
p.Start()
Dim s As String, err As String
Do
s = p.StandardOutpu t.ReadLine
err = p.StandardError .ReadLine
If Not s Is Nothing Then txtResults.Text += s + Environment.New Line
If Not err Is Nothing Then txtResults.Text += err +
Environment.New Line
Loop Until s Is Nothing
p.Dispose()
End Sub

Nov 18 '05 #1
7 1358
See this it should help:-
http://www.developer.com/security/article.php/3065031

"Bonj" <Bo**@discussio ns.microsoft.co m> wrote in message
news:33******** *************** ***********@mic rosoft.com...
Hi
I made a naff web application which uses the impersonation method in MSDN
(can't find it now, but it basically revolves around creating a token by
calling the LogonUser API, calling DuplicateToken API on it, and then calling w.Impersonate() where w is a System.Security .Principal.Wind owsIdentity
object). This is the only real point of the said web application if I'm
brutally honest with myself ;-) however it leaves me curious, as does any
test project!

I set up this web application, the idea of which being to shell commands on the web server and see the output in a webforms text box, from a remote
machine.
I thought the impersonation worked because all the return values were as
expected, and what's more a totally independent Environment.Use rName function returned the username I had impersonated. However, when I try to do
"dir "c:\documen ts and settings\bonj\* .txt" /b /s
from the web application, it returns 'file not found' but when I copy that
command into a DOS box (logged on as bonj) it returns a whole list of text
files. I'm suspicous that there's some permissions thing that windows is
hiding from me. What, though?

The code for the impersonation is this:

Public Class Impersonator
Implements IDisposable

Const LOGON32_LOGON_I NTERACTIVE As Int32 = 2
Const LOGON32_PROVIDE R_DEFAULT As Int32 = 0
Const SecurityImperso nation As Int32 = 2

Dim impersonationCo ntext As WindowsImperson ationContext

Declare Auto Function LogonUser Lib "advapi32.d ll" (ByVal lpszUserName
As String, _
ByVal lpszDomain As String, _
ByVal lpszPassword As String, _
ByVal dwLogonType As Int32, _
ByVal dwLogonProvider As Int32, _
ByRef phToken As IntPtr) As Int32
Declare Auto Function DuplicateToken Lib "advapi32.d ll" _
(ByVal ExistingTokenHa ndle As IntPtr, _
ByVal ImpersonationLe vel As Int32, _
ByRef DuplicateTokenH andle As IntPtr) As Int32

Public Function Impersonate(ByV al UserName As String, ByVal Domain As
String, ByVal Password As String) As Boolean

Dim tempWindowsIden tity As WindowsIdentity
Dim token As IntPtr
Dim tokenDuplicate As IntPtr

If LogonUser(UserN ame, Domain, password, LOGON32_LOGON_I NTERACTIVE, _ LOGON32_PROVIDE R_DEFAULT, token) <> 0 Then
If DuplicateToken( token, 2, tokenDuplicate) <> 0 Then
tempWindowsIden tity = New WindowsIdentity (tokenDuplicate )
impersonationCo ntext = tempWindowsIden tity.Impersonat e()
Return Not (impersonationC ontext Is Nothing)
End If
End If
End Function

Public Sub Dispose() Implements System.IDisposa ble.Dispose
If Not impersonationCo ntext Is Nothing Then
impersonationCo ntext.Undo()
End Sub
End Class
and the code for the cmdCommand click button on the web form is:

Private Sub cmdGo_Click(ByV al sender As System.Object, ByVal e As
System.EventArg s) Handles cmdGo.Click
txtResults.Text = ""
Dim p As New Process
Dim psi As New
ProcessStartInf o(Environment.G etEnvironmentVa riable("comspec "), _
"/c """ + txtCommand.Text + """")
psi.UseShellExe cute = False
psi.CreateNoWin dow = True
psi.RedirectSta ndardOutput = True
psi.RedirectSta ndardError = True
psi.WindowStyle = ProcessWindowSt yle.Hidden
p.StartInfo = psi
p.Start()
Dim s As String, err As String
Do
s = p.StandardOutpu t.ReadLine
err = p.StandardError .ReadLine
If Not s Is Nothing Then txtResults.Text += s + Environment.New Line If Not err Is Nothing Then txtResults.Text += err +
Environment.New Line
Loop Until s Is Nothing
p.Dispose()
End Sub

Nov 18 '05 #2
Hi,

Well, the error is correct - there is no executable named "dir" (or dir.exe
or dir.bat etc) in the path. You should execute cmd.exe and then pass "dir"
as argument.

Another point is that the System.IO namespace has ready classes that make
one's life easier when in need to work with the filesystem (eg the static
method GetFiles(string , string) of the System.IO.Direc tory class returns the
results in the most convinient format - a string array; see:
http://msdn.microsoft.com/library/en...FilesTopic.asp)

Greetings
Martin
"Bonj" <Bo**@discussio ns.microsoft.co m> wrote in message
news:33******** *************** ***********@mic rosoft.com...
Hi
I made a naff web application which uses the impersonation method in MSDN
(can't find it now, but it basically revolves around creating a token by
calling the LogonUser API, calling DuplicateToken API on it, and then calling w.Impersonate() where w is a System.Security .Principal.Wind owsIdentity
object). This is the only real point of the said web application if I'm
brutally honest with myself ;-) however it leaves me curious, as does any
test project!

I set up this web application, the idea of which being to shell commands on the web server and see the output in a webforms text box, from a remote
machine.
I thought the impersonation worked because all the return values were as
expected, and what's more a totally independent Environment.Use rName function returned the username I had impersonated. However, when I try to do
"dir "c:\documen ts and settings\bonj\* .txt" /b /s
from the web application, it returns 'file not found' but when I copy that
command into a DOS box (logged on as bonj) it returns a whole list of text
files. I'm suspicous that there's some permissions thing that windows is
hiding from me. What, though?

The code for the impersonation is this:

Public Class Impersonator
Implements IDisposable

Const LOGON32_LOGON_I NTERACTIVE As Int32 = 2
Const LOGON32_PROVIDE R_DEFAULT As Int32 = 0
Const SecurityImperso nation As Int32 = 2

Dim impersonationCo ntext As WindowsImperson ationContext

Declare Auto Function LogonUser Lib "advapi32.d ll" (ByVal lpszUserName
As String, _
ByVal lpszDomain As String, _
ByVal lpszPassword As String, _
ByVal dwLogonType As Int32, _
ByVal dwLogonProvider As Int32, _
ByRef phToken As IntPtr) As Int32
Declare Auto Function DuplicateToken Lib "advapi32.d ll" _
(ByVal ExistingTokenHa ndle As IntPtr, _
ByVal ImpersonationLe vel As Int32, _
ByRef DuplicateTokenH andle As IntPtr) As Int32

Public Function Impersonate(ByV al UserName As String, ByVal Domain As
String, ByVal Password As String) As Boolean

Dim tempWindowsIden tity As WindowsIdentity
Dim token As IntPtr
Dim tokenDuplicate As IntPtr

If LogonUser(UserN ame, Domain, password, LOGON32_LOGON_I NTERACTIVE, _ LOGON32_PROVIDE R_DEFAULT, token) <> 0 Then
If DuplicateToken( token, 2, tokenDuplicate) <> 0 Then
tempWindowsIden tity = New WindowsIdentity (tokenDuplicate )
impersonationCo ntext = tempWindowsIden tity.Impersonat e()
Return Not (impersonationC ontext Is Nothing)
End If
End If
End Function

Public Sub Dispose() Implements System.IDisposa ble.Dispose
If Not impersonationCo ntext Is Nothing Then
impersonationCo ntext.Undo()
End Sub
End Class
and the code for the cmdCommand click button on the web form is:

Private Sub cmdGo_Click(ByV al sender As System.Object, ByVal e As
System.EventArg s) Handles cmdGo.Click
txtResults.Text = ""
Dim p As New Process
Dim psi As New
ProcessStartInf o(Environment.G etEnvironmentVa riable("comspec "), _
"/c """ + txtCommand.Text + """")
psi.UseShellExe cute = False
psi.CreateNoWin dow = True
psi.RedirectSta ndardOutput = True
psi.RedirectSta ndardError = True
psi.WindowStyle = ProcessWindowSt yle.Hidden
p.StartInfo = psi
p.Start()
Dim s As String, err As String
Do
s = p.StandardOutpu t.ReadLine
err = p.StandardError .ReadLine
If Not s Is Nothing Then txtResults.Text += s + Environment.New Line If Not err Is Nothing Then txtResults.Text += err +
Environment.New Line
Loop Until s Is Nothing
p.Dispose()
End Sub

Nov 18 '05 #3
No, not really - it's mainly about "XML metabase" whatever that is, there is
a little bit about impersonation but it's a brief section about how to do it
via the config file, which is hardcoded and goes against my principles.

Thanks anyway though

Cheers

Nov 18 '05 #4
No, sorry, I'm not actually running that.
I should have explained that:
The name of the process I'm calling is cmd.exe, retrieved by calling
Environment.Get EnvironmentVari able("comspec")

and the argument is
"/c dir "c:\doucume nts and ......./s /b"
and that it works perfectly for directories other than my personal one in
"c:\documen ts and settings", which is why I titled the post "impersonat ion
...." rather than something to do with shelling processes.
Thanks anyway

Cheers

"Martin Dechev" wrote:
Hi,

Well, the error is correct - there is no executable named "dir" (or dir.exe
or dir.bat etc) in the path. You should execute cmd.exe and then pass "dir"
as argument.

Another point is that the System.IO namespace has ready classes that make
one's life easier when in need to work with the filesystem (eg the static
method GetFiles(string , string) of the System.IO.Direc tory class returns the
results in the most convinient format - a string array; see:
http://msdn.microsoft.com/library/en...FilesTopic.asp)

Greetings
Martin
"Bonj" <Bo**@discussio ns.microsoft.co m> wrote in message
news:33******** *************** ***********@mic rosoft.com...
Hi
I made a naff web application which uses the impersonation method in MSDN
(can't find it now, but it basically revolves around creating a token by
calling the LogonUser API, calling DuplicateToken API on it, and then

calling
w.Impersonate() where w is a System.Security .Principal.Wind owsIdentity
object). This is the only real point of the said web application if I'm
brutally honest with myself ;-) however it leaves me curious, as does any
test project!

I set up this web application, the idea of which being to shell commands

on
the web server and see the output in a webforms text box, from a remote
machine.
I thought the impersonation worked because all the return values were as
expected, and what's more a totally independent Environment.Use rName

function
returned the username I had impersonated. However, when I try to do
"dir "c:\documen ts and settings\bonj\* .txt" /b /s
from the web application, it returns 'file not found' but when I copy that
command into a DOS box (logged on as bonj) it returns a whole list of text
files. I'm suspicous that there's some permissions thing that windows is
hiding from me. What, though?

The code for the impersonation is this:

Public Class Impersonator
Implements IDisposable

Const LOGON32_LOGON_I NTERACTIVE As Int32 = 2
Const LOGON32_PROVIDE R_DEFAULT As Int32 = 0
Const SecurityImperso nation As Int32 = 2

Dim impersonationCo ntext As WindowsImperson ationContext

Declare Auto Function LogonUser Lib "advapi32.d ll" (ByVal lpszUserName
As String, _
ByVal lpszDomain As String, _
ByVal lpszPassword As String, _
ByVal dwLogonType As Int32, _
ByVal dwLogonProvider As Int32, _
ByRef phToken As IntPtr) As Int32
Declare Auto Function DuplicateToken Lib "advapi32.d ll" _
(ByVal ExistingTokenHa ndle As IntPtr, _
ByVal ImpersonationLe vel As Int32, _
ByRef DuplicateTokenH andle As IntPtr) As Int32

Public Function Impersonate(ByV al UserName As String, ByVal Domain As
String, ByVal Password As String) As Boolean

Dim tempWindowsIden tity As WindowsIdentity
Dim token As IntPtr
Dim tokenDuplicate As IntPtr

If LogonUser(UserN ame, Domain, password,

LOGON32_LOGON_I NTERACTIVE, _
LOGON32_PROVIDE R_DEFAULT, token) <> 0 Then
If DuplicateToken( token, 2, tokenDuplicate) <> 0 Then
tempWindowsIden tity = New WindowsIdentity (tokenDuplicate )
impersonationCo ntext = tempWindowsIden tity.Impersonat e()
Return Not (impersonationC ontext Is Nothing)
End If
End If
End Function

Public Sub Dispose() Implements System.IDisposa ble.Dispose
If Not impersonationCo ntext Is Nothing Then
impersonationCo ntext.Undo()
End Sub
End Class
and the code for the cmdCommand click button on the web form is:

Private Sub cmdGo_Click(ByV al sender As System.Object, ByVal e As
System.EventArg s) Handles cmdGo.Click
txtResults.Text = ""
Dim p As New Process
Dim psi As New
ProcessStartInf o(Environment.G etEnvironmentVa riable("comspec "), _
"/c """ + txtCommand.Text + """")
psi.UseShellExe cute = False
psi.CreateNoWin dow = True
psi.RedirectSta ndardOutput = True
psi.RedirectSta ndardError = True
psi.WindowStyle = ProcessWindowSt yle.Hidden
p.StartInfo = psi
p.Start()
Dim s As String, err As String
Do
s = p.StandardOutpu t.ReadLine
err = p.StandardError .ReadLine
If Not s Is Nothing Then txtResults.Text += s +

Environment.New Line
If Not err Is Nothing Then txtResults.Text += err +
Environment.New Line
Loop Until s Is Nothing
p.Dispose()
End Sub


Nov 18 '05 #5
Another point is that the System.IO namespace has ready classes that make
one's life easier when in need to work with the filesystem (eg the static
method GetFiles(string , string) of the System.IO.Direc tory class returns the
results in the most convinient format - a string array; see:
http://msdn.microsoft.com/library/en-
I'm not specifically trying to find out what files are on the drive. I'm
just trying to setup a process whereby I can run whatever command I want *on*
my own PC, *from* any other. The "dir" was just an example command, but then
it led me onto this folder permissions thing...
Yeah, yeah, I could use remoting. But, I could just give ASPNET's process
higher permissions. But I don't want to do that. I want to be sure
impersonation works...


us/cpref/html/frlrfSystemIODi rectoryClassGet FilesTopic.asp)
Greetings
Martin
"Bonj" <Bo**@discussio ns.microsoft.co m> wrote in message
news:33******** *************** ***********@mic rosoft.com...
Hi
I made a naff web application which uses the impersonation method in MSDN
(can't find it now, but it basically revolves around creating a token by
calling the LogonUser API, calling DuplicateToken API on it, and then

calling
w.Impersonate() where w is a System.Security .Principal.Wind owsIdentity
object). This is the only real point of the said web application if I'm
brutally honest with myself ;-) however it leaves me curious, as does any
test project!

I set up this web application, the idea of which being to shell commands

on
the web server and see the output in a webforms text box, from a remote
machine.
I thought the impersonation worked because all the return values were as
expected, and what's more a totally independent Environment.Use rName

function
returned the username I had impersonated. However, when I try to do
"dir "c:\documen ts and settings\bonj\* .txt" /b /s
from the web application, it returns 'file not found' but when I copy that
command into a DOS box (logged on as bonj) it returns a whole list of text
files. I'm suspicous that there's some permissions thing that windows is
hiding from me. What, though?

The code for the impersonation is this:

Public Class Impersonator
Implements IDisposable

Const LOGON32_LOGON_I NTERACTIVE As Int32 = 2
Const LOGON32_PROVIDE R_DEFAULT As Int32 = 0
Const SecurityImperso nation As Int32 = 2

Dim impersonationCo ntext As WindowsImperson ationContext

Declare Auto Function LogonUser Lib "advapi32.d ll" (ByVal lpszUserName
As String, _
ByVal lpszDomain As String, _
ByVal lpszPassword As String, _
ByVal dwLogonType As Int32, _
ByVal dwLogonProvider As Int32, _
ByRef phToken As IntPtr) As Int32
Declare Auto Function DuplicateToken Lib "advapi32.d ll" _
(ByVal ExistingTokenHa ndle As IntPtr, _
ByVal ImpersonationLe vel As Int32, _
ByRef DuplicateTokenH andle As IntPtr) As Int32

Public Function Impersonate(ByV al UserName As String, ByVal Domain As
String, ByVal Password As String) As Boolean

Dim tempWindowsIden tity As WindowsIdentity
Dim token As IntPtr
Dim tokenDuplicate As IntPtr

If LogonUser(UserN ame, Domain, password,

LOGON32_LOGON_I NTERACTIVE, _
LOGON32_PROVIDE R_DEFAULT, token) <> 0 Then
If DuplicateToken( token, 2, tokenDuplicate) <> 0 Then
tempWindowsIden tity = New WindowsIdentity (tokenDuplicate )
impersonationCo ntext = tempWindowsIden tity.Impersonat e()
Return Not (impersonationC ontext Is Nothing)
End If
End If
End Function

Public Sub Dispose() Implements System.IDisposa ble.Dispose
If Not impersonationCo ntext Is Nothing Then
impersonationCo ntext.Undo()
End Sub
End Class
and the code for the cmdCommand click button on the web form is:

Private Sub cmdGo_Click(ByV al sender As System.Object, ByVal e As
System.EventArg s) Handles cmdGo.Click
txtResults.Text = ""
Dim p As New Process
Dim psi As New
ProcessStartInf o(Environment.G etEnvironmentVa riable("comspec "), _
"/c """ + txtCommand.Text + """")
psi.UseShellExe cute = False
psi.CreateNoWin dow = True
psi.RedirectSta ndardOutput = True
psi.RedirectSta ndardError = True
psi.WindowStyle = ProcessWindowSt yle.Hidden
p.StartInfo = psi
p.Start()
Dim s As String, err As String
Do
s = p.StandardOutpu t.ReadLine
err = p.StandardError .ReadLine
If Not s Is Nothing Then txtResults.Text += s +

Environment.New Line
If Not err Is Nothing Then txtResults.Text += err +
Environment.New Line
Loop Until s Is Nothing
p.Dispose()
End Sub


Nov 18 '05 #6
Forgive me if I am misinterpreting what you are saying.

Running an .exe across a network will not cause it to execute on the machine
where the .exe resides. It will still execute on the machine doing the
calling.

There is a tool in the resourcekit that will allow your to start a process
on another machine. (can't remember the name right now)

There is also a way with Windows Script Host to start a process remotely.

Greg

I'm not specifically trying to find out what files are on the drive. I'm
just trying to setup a process whereby I can run whatever command I want
*on*
my own PC, *from* any other. The "dir" was just an example command, but
then
it led me onto this folder permissions thing...
Yeah, yeah, I could use remoting. But, I could just give ASPNET's process
higher permissions. But I don't want to do that. I want to be sure
impersonation works...

Nov 18 '05 #7
Hi,

Impersonation works. Although running executables and starting batches is
possible, it is not recommended doing it from the webserver because it is a
non-interactive execution - there's noone to respond to dialog boxes,
requested input, etc. It is always better if you can perform the tasks you
need using the provided framework classes or in cases when there is nothing
ready use platform invoke.

Greetings
Martin
"Bonj" <Bo**@discussio ns.microsoft.co m> wrote in message
news:1E******** *************** ***********@mic rosoft.com...
Another point is that the System.IO namespace has ready classes that make one's life easier when in need to work with the filesystem (eg the static method GetFiles(string , string) of the System.IO.Direc tory class returns the results in the most convinient format - a string array; see:
http://msdn.microsoft.com/library/en-
I'm not specifically trying to find out what files are on the drive. I'm
just trying to setup a process whereby I can run whatever command I want

*on* my own PC, *from* any other. The "dir" was just an example command, but then it led me onto this folder permissions thing...
Yeah, yeah, I could use remoting. But, I could just give ASPNET's process
higher permissions. But I don't want to do that. I want to be sure
impersonation works...


us/cpref/html/frlrfSystemIODi rectoryClassGet FilesTopic.asp)

Greetings
Martin
"Bonj" <Bo**@discussio ns.microsoft.co m> wrote in message
news:33******** *************** ***********@mic rosoft.com...
Hi
I made a naff web application which uses the impersonation method in MSDN (can't find it now, but it basically revolves around creating a token by calling the LogonUser API, calling DuplicateToken API on it, and then

calling
w.Impersonate() where w is a System.Security .Principal.Wind owsIdentity
object). This is the only real point of the said web application if I'm brutally honest with myself ;-) however it leaves me curious, as does any test project!

I set up this web application, the idea of which being to shell commands
on
the web server and see the output in a webforms text box, from a

remote machine.
I thought the impersonation worked because all the return values were as expected, and what's more a totally independent Environment.Use rName

function
returned the username I had impersonated. However, when I try to do
"dir "c:\documen ts and settings\bonj\* .txt" /b /s
from the web application, it returns 'file not found' but when I copy that command into a DOS box (logged on as bonj) it returns a whole list of text files. I'm suspicous that there's some permissions thing that windows is hiding from me. What, though?

The code for the impersonation is this:

Public Class Impersonator
Implements IDisposable

Const LOGON32_LOGON_I NTERACTIVE As Int32 = 2
Const LOGON32_PROVIDE R_DEFAULT As Int32 = 0
Const SecurityImperso nation As Int32 = 2

Dim impersonationCo ntext As WindowsImperson ationContext

Declare Auto Function LogonUser Lib "advapi32.d ll" (ByVal lpszUserName As String, _
ByVal lpszDomain As String, _
ByVal lpszPassword As String, _
ByVal dwLogonType As Int32, _
ByVal dwLogonProvider As Int32, _
ByRef phToken As IntPtr) As Int32
Declare Auto Function DuplicateToken Lib "advapi32.d ll" _
(ByVal ExistingTokenHa ndle As IntPtr, _
ByVal ImpersonationLe vel As Int32, _
ByRef DuplicateTokenH andle As IntPtr) As Int32

Public Function Impersonate(ByV al UserName As String, ByVal Domain As String, ByVal Password As String) As Boolean

Dim tempWindowsIden tity As WindowsIdentity
Dim token As IntPtr
Dim tokenDuplicate As IntPtr

If LogonUser(UserN ame, Domain, password,

LOGON32_LOGON_I NTERACTIVE, _
LOGON32_PROVIDE R_DEFAULT, token) <> 0 Then
If DuplicateToken( token, 2, tokenDuplicate) <> 0 Then
tempWindowsIden tity = New WindowsIdentity (tokenDuplicate ) impersonationCo ntext = tempWindowsIden tity.Impersonat e() Return Not (impersonationC ontext Is Nothing)
End If
End If
End Function

Public Sub Dispose() Implements System.IDisposa ble.Dispose
If Not impersonationCo ntext Is Nothing Then
impersonationCo ntext.Undo()
End Sub
End Class
and the code for the cmdCommand click button on the web form is:

Private Sub cmdGo_Click(ByV al sender As System.Object, ByVal e As
System.EventArg s) Handles cmdGo.Click
txtResults.Text = ""
Dim p As New Process
Dim psi As New
ProcessStartInf o(Environment.G etEnvironmentVa riable("comspec "), _
"/c """ + txtCommand.Text + """")
psi.UseShellExe cute = False
psi.CreateNoWin dow = True
psi.RedirectSta ndardOutput = True
psi.RedirectSta ndardError = True
psi.WindowStyle = ProcessWindowSt yle.Hidden
p.StartInfo = psi
p.Start()
Dim s As String, err As String
Do
s = p.StandardOutpu t.ReadLine
err = p.StandardError .ReadLine
If Not s Is Nothing Then txtResults.Text += s +

Environment.New Line
If Not err Is Nothing Then txtResults.Text += err +
Environment.New Line
Loop Until s Is Nothing
p.Dispose()
End Sub


Nov 18 '05 #8

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

Similar topics

12
2561
by: Anil Krishnamurthy | last post by:
We have an ASP.NET application that uses COM objects through Interop. The web application requires access to network and database resources and hence, needs to impersonate a domain account. The problem is that even when it is configured to run under a certain identity through Web.config, the impersonation is not carried through to COM library. Consequently, the code in COM object runs under a local account and any code that needs to access...
1
3952
by: techfuzz | last post by:
I'm posting my problem experience and solution I found here for other ASP.NET developers. I have a web application that uses Forms Authentication with Active Directory to control access. In this web application, I have search page that utilizes the Windows Indexing Service (MSIDXS provider). For reasons I'm not aware of at this time, setting <identity impersonation="true" /> in the web.config causes an error whenever you try to search.
0
1579
by: Peter Afonin | last post by:
Hello: When I try to access a SQL server or a network share from an ASP.Net application that I run on my computer, I run into security problems (for instance, I cannot execute DTS package using Trusted connection or get a file information using FileInfo class). This is probably because my application is running under PETER\ASPNET account, where PETER is my computer's name. I can solve this problem by using Impersonation. However, when...
3
2666
by: cjk | last post by:
Issue Our web application requires access to write to a custom event log, yet access is denied. This access is denied because we are using impersonation, and our end-users do not (should not) have permissions to write to a custom event log. We would like to know if someone out there has resolved this problem without incorporating registry hacks, elevating end-user account permissions to admin OR calling native code to logon as the account...
3
6503
by: Wm. Scott Miller | last post by:
What is the difference between using a username and password in the processmodel section vs using one in impersonation in the machine.config file? What are the advantages of each and what are the reasons for using each? Thanks for any replies, Scott
7
1145
by: Bonj | last post by:
Hi I made a naff web application which uses the impersonation method in MSDN (can't find it now, but it basically revolves around creating a token by calling the LogonUser API, calling DuplicateToken API on it, and then calling w.Impersonate() where w is a System.Security.Principal.WindowsIdentity object). This is the only real point of the said web application if I'm brutally honest with myself ;-) however it leaves me curious, as does...
3
1571
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
1
1877
by: Patrick | last post by:
I have an ASP.NET web service whose Web.Config is set to use impersonation <authentication mode="Windows" /> <identity impersonate="true" /> Within a Web Method, I want to use Multi-threading to spawn off an asynchronous process, as it takes quite long to return. How could I get the worker thread to runas the same impersonated user on ASP.NET?
1
1531
by: zhuang | last post by:
Dear all, I found a very interesting thing about viewing crystal report (located on network drive) with asp.net application. To do the impersonation, modify web.config does not work, you have to modify machine.config. which is not recommended. However, there is no way around. To prove I did the impersonation properly, I did the below test.
0
8242
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
8177
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
8629
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...
0
7170
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6112
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
5570
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
4183
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1793
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1488
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.