473,473 Members | 2,145 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Impersonate user from ASP.NET - access to network file share

Hello!

I have an ASP.NET application (1.1 framework) that needs to be able to
read/write files on a network share. The access to this file share
will be fairly restricted, so I need to impersonate a specific user
account on our domain in order to gain access. The impersonation is
only needed for the sections that reads/writes files. I have tried
using the code from http://support.microsoft.com/default...N-US;Q306158#4
and many other similar sources with no success. I do not get any
errors, but I am not logged in using the username and passoword I
provide so I cannot access the network (it remains the anonymous
user). I have tried putting the impersonation code into a Class
Library and calling that from the web application with the same
results.

I must be doing something wrong. Any help would be appreciated.
(see code snippets below - irrelevant code has been removed)

Thank you,
Michelle
** CLASS LIBRARY **
****************************

Imports System.IO
Imports System.String
Imports System.Security.Principal
Imports System.Security

Public Class PerformanceReviewAttachment
Private Shared LOGON32_LOGON_INTERACTIVE As Integer = 2
Private Shared LOGON32_PROVIDER_DEFAULT As Integer = 0
Private Shared impersonationContext As WindowsImpersonationContext

Declare Function LogonUserA Lib "advapi32.dll" (ByVal lpszUsername
As String, _
ByVal lpszDomain As String, _
ByVal lpszPassword As String, _
ByVal dwLogonType As Integer, _
ByVal dwLogonProvider As Integer, _
ByRef phToken As IntPtr) As Integer

Declare Auto Function DuplicateToken Lib "advapi32.dll" ( _
ByVal ExistingTokenHandle As IntPtr, _
ByVal ImpersonationLevel As Integer, _
ByRef DuplicateTokenHandle As IntPtr) As
Integer

Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle
As IntPtr) As Long


Shared Function impersonateValidUser(ByVal userName As String,
ByVal domain As String, ByVal password As String) As Boolean
Dim tempWindowsIdentity As WindowsIdentity
Dim token As IntPtr = IntPtr.Zero
Dim tokenDuplicate As IntPtr = IntPtr.Zero
impersonateValidUser = False

If RevertToSelf() <> 0 Then
If LogonUserA(userName, domain, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
tempWindowsIdentity = New
WindowsIdentity(tokenDuplicate)
impersonationContext =
tempWindowsIdentity.Impersonate()
If Not impersonationContext Is Nothing Then
impersonateValidUser = True
End If
End If
End If
End If
If Not tokenDuplicate.Equals(IntPtr.Zero) Then
CloseHandle(tokenDuplicate)
End If
If Not token.Equals(IntPtr.Zero) Then
CloseHandle(token)
End If
End Function

Shared Sub undoImpersonation()
impersonationContext.Undo()
End Sub
End Class


** WEB FORM **
****************************

Private Sub Submit1_ServerClick(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Submit1.ServerClick
Try

If classLibrary.impersonateValidUser("user",
"domain", "pwd") Then
File1.PostedFile.SaveAs(strFileName)
classLibrary.undoImpersonation()
Else
Throw New ApplicationException("Failed")
End If
Catch Ex As Exception
lblErrorMessage.Text = ex.Message
End Try
End Sub
Jul 21 '05 #1
8 9737
1.You should not use LOGON32_LOGON_INTERACTIVE, instead you should Call
LogonUser specifying LOGON32_LOGON_NETWORK_CLEARTEXT (8) or
LOGON32_LOGON_NEW_CREDENTIALS (9) as logontype.
2. You should not call DuplicateToken, instead you should use the token
obtained from LogonUser to create the temp WindowsIdentity.

Willy.

PS. LOGON32_LOGON_NEW_CREDENTIALS can only be used by Domain credentials on
a W2K AD domain.
"Michelle" <Mi******@bwalk.com> wrote in message
news:92**************************@posting.google.c om...
Hello!

I have an ASP.NET application (1.1 framework) that needs to be able to
read/write files on a network share. The access to this file share
will be fairly restricted, so I need to impersonate a specific user
account on our domain in order to gain access. The impersonation is
only needed for the sections that reads/writes files. I have tried
using the code from
http://support.microsoft.com/default...N-US;Q306158#4
and many other similar sources with no success. I do not get any
errors, but I am not logged in using the username and passoword I
provide so I cannot access the network (it remains the anonymous
user). I have tried putting the impersonation code into a Class
Library and calling that from the web application with the same
results.

I must be doing something wrong. Any help would be appreciated.
(see code snippets below - irrelevant code has been removed)

Thank you,
Michelle
** CLASS LIBRARY **
****************************

Imports System.IO
Imports System.String
Imports System.Security.Principal
Imports System.Security

Public Class PerformanceReviewAttachment
Private Shared LOGON32_LOGON_INTERACTIVE As Integer = 2
Private Shared LOGON32_PROVIDER_DEFAULT As Integer = 0
Private Shared impersonationContext As WindowsImpersonationContext

Declare Function LogonUserA Lib "advapi32.dll" (ByVal lpszUsername
As String, _
ByVal lpszDomain As String, _
ByVal lpszPassword As String, _
ByVal dwLogonType As Integer, _
ByVal dwLogonProvider As Integer, _
ByRef phToken As IntPtr) As Integer

Declare Auto Function DuplicateToken Lib "advapi32.dll" ( _
ByVal ExistingTokenHandle As IntPtr, _
ByVal ImpersonationLevel As Integer, _
ByRef DuplicateTokenHandle As IntPtr) As
Integer

Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle
As IntPtr) As Long


Shared Function impersonateValidUser(ByVal userName As String,
ByVal domain As String, ByVal password As String) As Boolean
Dim tempWindowsIdentity As WindowsIdentity
Dim token As IntPtr = IntPtr.Zero
Dim tokenDuplicate As IntPtr = IntPtr.Zero
impersonateValidUser = False

If RevertToSelf() <> 0 Then
If LogonUserA(userName, domain, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
tempWindowsIdentity = New
WindowsIdentity(tokenDuplicate)
impersonationContext =
tempWindowsIdentity.Impersonate()
If Not impersonationContext Is Nothing Then
impersonateValidUser = True
End If
End If
End If
End If
If Not tokenDuplicate.Equals(IntPtr.Zero) Then
CloseHandle(tokenDuplicate)
End If
If Not token.Equals(IntPtr.Zero) Then
CloseHandle(token)
End If
End Function

Shared Sub undoImpersonation()
impersonationContext.Undo()
End Sub
End Class


** WEB FORM **
****************************

Private Sub Submit1_ServerClick(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Submit1.ServerClick
Try

If classLibrary.impersonateValidUser("user",
"domain", "pwd") Then
File1.PostedFile.SaveAs(strFileName)
classLibrary.undoImpersonation()
Else
Throw New ApplicationException("Failed")
End If
Catch Ex As Exception
lblErrorMessage.Text = ex.Message
End Try
End Sub

Jul 21 '05 #2
Hi Willy!

Thank you for your reply. I have implemented the changes you
suggested (see snippet below), however LogonA still returns 0. Could
the NT Domain be preventing the logon somehow? I have not adjusted any
security on the web server, could something there be preventing the
logon? I do not get any errors, can I assume that the unmanaged code
is being called properly?

Sorry for all of the questions! Thank you.
Michelle
**********************************
If RevertToSelf() <> 0 Then
If LogonUserA(userName, domain, password,
LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_PROVIDER_DEFAULT, token) <> 0
Then
tempWindowsIdentity = New WindowsIdentity(token)
impersonationContext =
tempWindowsIdentity.Impersonate()
If Not impersonationContext Is Nothing Then
impersonationSucceeded = True
End If
End If
End If
**********************************

Jul 21 '05 #3
On 8 Dec 2004 11:31:21 -0800, Mi******@bwalk.com (Michelle) wrote:

¤ Hello!
¤
¤ I have an ASP.NET application (1.1 framework) that needs to be able to
¤ read/write files on a network share. The access to this file share
¤ will be fairly restricted, so I need to impersonate a specific user
¤ account on our domain in order to gain access. The impersonation is
¤ only needed for the sections that reads/writes files. I have tried
¤ using the code from http://support.microsoft.com/default...N-US;Q306158#4
¤ and many other similar sources with no success. I do not get any
¤ errors, but I am not logged in using the username and passoword I
¤ provide so I cannot access the network (it remains the anonymous
¤ user). I have tried putting the impersonation code into a Class
¤ Library and calling that from the web application with the same
¤ results.
¤

If you're accessing a resource that is not located on the web server then you will probably need to
implement delegation:

How to configure an ASP.NET application for a delegation scenario
http://support.microsoft.com/default...b;en-us;810572
Paul ~~~ pc******@ameritech.net
Microsoft MVP (Visual Basic)
Jul 21 '05 #4
Hi Paul,

Thank you for posting that link. I have a question: Impersonation and
delegation do not directly rely on eachother, do they? What I mean is,
I can have impersonation working but not be able to access network
resources because of delegation? If so, then I can wait to implement
the delegation changes recommended in the link until I get
impersonation working (LogonUserA always returns 0)? I ask because I'd
have to clear many of the delegation changes with the sys-admin before
going ahead with them, and that could take a while.

Also, I thought I'd mention as an FYI in case this could help point out
why I have a problem with impersonation: I cannot remove anonymous
access from the web site and have only Integrated authentication. Not
everyone who logs into the application has their own computer or NT
login and some log in from home, so I use a custom authentication that
I built for when they log in. So, on the 1 page only, I need to
impersonate a user on the NT Domain that the sys-admin will create so
that the user has access to the directory on the network where the
files will be saved.

Thanks again!
Michelle

Jul 21 '05 #5
If LogonUser returns <> 0
call Marshal.getLastWin32Error() to retrieve the Win32 error code.

Are you sure you pass a valid user, machine and password as arguments?
Say you are user alice on Alice's machine want to authenticate as user Bob
on BobsMachine, then you need to pass "Bob", "BobsMachine", "BobsPwd".

Willy.

<Mi******@bwalk.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Hi Willy!

Thank you for your reply. I have implemented the changes you
suggested (see snippet below), however LogonA still returns 0. Could
the NT Domain be preventing the logon somehow? I have not adjusted any
security on the web server, could something there be preventing the
logon? I do not get any errors, can I assume that the unmanaged code
is being called properly?

Sorry for all of the questions! Thank you.
Michelle
**********************************
If RevertToSelf() <> 0 Then
If LogonUserA(userName, domain, password,
LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_PROVIDER_DEFAULT, token) <> 0
Then
tempWindowsIdentity = New WindowsIdentity(token)
impersonationContext =
tempWindowsIdentity.Impersonate()
If Not impersonationContext Is Nothing Then
impersonationSucceeded = True
End If
End If
End If
**********************************

Jul 21 '05 #6
Hi all!!

I just wanted to let you know that I have conceeded and just put
<identity impersonate="true" userName="accountname" password="password"
/> in the web config. This works perfectly. I origionally didnt' want
to set up impersonation for the whole site, but hopefully my sysadmin
will clear it and all will be well.

Thanks!!
Michelle

Jul 21 '05 #7
You could just move the part of the application that reads and writes files
to its own application space and use impersonation there only.

--
Regards

John Timney
ASP.NET MVP
Microsoft Regional Director

<Mi******@bwalk.com> wrote in message
news:11*********************@z14g2000cwz.googlegro ups.com...
Hi all!!

I just wanted to let you know that I have conceeded and just put
<identity impersonate="true" userName="accountname" password="password"
/> in the web config. This works perfectly. I origionally didnt' want
to set up impersonation for the whole site, but hopefully my sysadmin
will clear it and all will be well.

Thanks!!
Michelle

Jul 21 '05 #8
On 9 Dec 2004 12:50:39 -0800, Mi******@bwalk.com wrote:

¤ Hi all!!
¤
¤ I just wanted to let you know that I have conceeded and just put
¤ <identity impersonate="true" userName="accountname" password="password"
¤ /> in the web config. This works perfectly. I origionally didnt' want
¤ to set up impersonation for the whole site, but hopefully my sysadmin
¤ will clear it and all will be well.

That probably works because the user name and password are clear text at the web server and can be
passed in response to authentication challenges from remote resources.

In answer to your other question, delegation is the next step after impersonation when attempting to
access remote resources. If you're using a mechanism where the user ID and password are encrypted
then you need to implement the delegation mechanism w/Kerberos.

If your credentials are clear text at the web server such as in Basic authentication with no SSL
(which of course isn't particularly secure) then those credentials can be used in response to
authentication challenges when access remote resources.

You can find more info at the below link:

http://msdn.microsoft.com/library/de...SecNetch08.asp
Paul ~~~ pc******@ameritech.net
Microsoft MVP (Visual Basic)
Jul 21 '05 #9

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

Similar topics

12
by: Nils M. Lunde | last post by:
Hi! I've made a Web Service using C# that is using impersonation. The WS is working fine on WinXP and Win2003Server, but I'm having problem getting it to work on Win2000. The problem is that...
8
by: BLiTZWiNG | last post by:
After playing with the code shown and utilising Willy Denyottes' help, I have come to the conclusion that there is some form of difference between the managed WindowsIdentity.Impersonate() over the...
2
by: Divya | last post by:
Hello, I am developing a simple move file utility to move files from one domain to another in the same internal network. My program runs fine when it reads the parameters (user, domain, password...
8
by: Pete Wittig | last post by:
Hello, I am wondering if it is possible to create a networked application with C# that is seen as a windows user. For example, if Bob logged onto windows and then started the application, any...
2
by: Peter O'Reilly | last post by:
I am experiencing difficulty access a mapped network drive in an ASP.NET application. While using the .Net framework v 1.1 implementation of System.IO.Directory.Exists(), it fails to recognize a...
3
by: Kathy Burke | last post by:
Hi. Totally lost on this one (ok, I admit I'm USUALLY lost!). All works fine in dev environment (P4, localhost server IIS, XP Pro) Asp.net and .Net 1.1 In order to access doc files needed for...
6
by: Bjoern Wolfgardt | last post by:
Hi NG, I have written some Apps in ASP.NET that access a SQL Server on another machine. I never had a problem doing this in IIS5(.1). Most Apps are Intranet Application where I use the...
8
by: Michelle | last post by:
Hello! I have an ASP.NET application (1.1 framework) that needs to be able to read/write files on a network share. The access to this file share will be fairly restricted, so I need to...
2
by: rockdale | last post by:
Hi, all: My asp.net application calles MS speech 5.1 and generate a wav file on server's path. Everything runs perfectly on my development machine. But when I move the appl to production server,...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
1
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...
0
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...
1
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
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.