Must Impersonate to access file on network-file-server, Why?? Please help I'm desperate

Rate It (2)

Last post 08-03-2007 11:44 AM by naturehermit. 10 replies.

Sort Posts:

  • Must Impersonate to access file on network-file-server, Why?? Please help I'm desperate

    08-02-2007, 10:49 AM
    • Loading...
    • deblendewim
    • Joined on 12-20-2006, 4:32 PM
    • Antwerp, Belgium
    • Posts 943

    Hi all,

    I have an intranet setup, BUT, I still want my users to log-in to their applications (not my descision).

    Ok, My website setup is like this (web.config):

    <authentication mode="Forms">
    	<forms name="login" loginUrl="~/Login.aspx" defaultUrl="~/Main.aspx" timeout="90"/>
    </authentication>
    <identity impersonate="true"/>

     After the login, I try to read a file from a file server on the network:

      Using sr As StreamReader = New StreamReader("\\MYFILESERVER\MyFiles\Common.ini", Encoding.Default)

     

     When I do this, I get an error: Access to the path '\\MYFILESERVER\MyFiles\Common.ini' is denied.
    (I do have access to the file, I can access it, and the AD's "Everyone" user also has read permissions)

     When I programmatically Impersonate before the accessing of the file, all goes well !!!!!!!!!!!

    But what changes that? Why do I have to do that? I checked some properties/objects before and after the programatical impersonation and they where all the same before and after!!

    What I checked was :

    • System.Security.Principal.WindowsIdentity.GetCurrent()
    • system.Threading.Thread.CurrentPrincipal
    • system.Threading.Thread.CurrentPrincipal.Identity
    • system.Threading.Thread.CurrentThread
    • httpcontext.Current
    • httpcontext.Current.User.Identity
    • request.LogonUserIdentity.Name

    Again my questions .....

    Why do I have to impersonate again if I already have impersonate = true in web.config?
    What does that programatical impersonation change?
    How do I get rid of the programatical impersonation? this is realy a drag. I don't want to implement it every time I want to access a file on my network.

     

    Additions:

    When you look at table1 in the following article, they summerize the different combinations of authentication (windows/forms) and identity (true/false). Does this have something to do with what I'm experiencing? http://msdn2.microsoft.com/en-us/library/Aa480475.aspx   (But as I mentioned above, several of these properties returned the same result before and after programmatical impersonation)

     

    This is the code I use for the programmatical impersonation. (I call the impersonateValidUser to impersonate. I do this before I try to read a file from the network-fileServer. And I call undoImpersonation to end it.)

    #Region "Impersonation Code"
        Dim LOGON32_LOGON_INTERACTIVE As Integer = 2
        Dim LOGON32_PROVIDER_DEFAULT As Integer = 0
        Dim 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
    
    
        Public 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() 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
    
        Public Sub undoImpersonation()
            impersonationContext.Undo()
        End Sub
    
    #End Region
    
     


     

    All toughts/suggestions/comments/conciderations/.......... are welcome .... as I said, I'm realy desperate about this because I realy haven't got a clue of what is going on here Tongue Tied

    Kind regards,
    Wim

    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
  • Re: Must Impersonate to access file on network-file-server, Why?? Please help I'm desperate

    08-02-2007, 11:43 AM

    deblendewim:

    When I do this, I get an error: Access to the path '\\MYFILESERVER\MyFiles\Common.ini' is denied.
    (I do have access to the file, I can access it, and the AD's "Everyone" user also has read permissions)

    Neither you nor any account in the Everyone group is attempting access.  Normally it's the ASP.NET process account, unless you impersonate the logged in user account.  Since the ASP.NET process account doesn't have access, it's neither you nor in the Everyone group, it is appropriately denied.  Of course, all the users you didn't want to have access do since you chose to grant access to the Everyone group without knowing what accounts were in that group...

    Jeff

    Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
  • Re: Must Impersonate to access file on network-file-server, Why?? Please help I'm desperate

    08-02-2007, 3:33 PM
    • Loading...
    • deblendewim
    • Joined on 12-20-2006, 4:32 PM
    • Antwerp, Belgium
    • Posts 943

    Hi Jeff,

    Thanks for your quick reply!

    Ok, don't mind the Everyone, let's just say only I have access to the file.

    Why do I have to impersonate if in my web.config the tag identity says:               <identity impersonate="true" /> ?

    Also, in IIS the anonymous access is checked out. And only Integrated Windows Authentication is checked. So, shouldn't the application run under my domain credentials when I log in????

    Also, when I use this setup and in code I ask for the value of the following: request.LogonUserIdentity.Name, I get   MyDomain\MyUserName          (NOT MyLocalServerName\IUSR_blabla)?

     

    Ok, maybe my actual question should be, how can I let my application run under the logged-in domain-user account, and NOT the ASP.NET Process account???
    (But I taught I was already doing that with the configuration I mentioned in my first post??? no?)

     

    Kind regards,
    Wim

    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
  • Re: Must Impersonate to access file on network-file-server, Why?? Please help I'm desperate

    08-03-2007, 12:22 AM
    Answer
    • Loading...
    • Bernado
    • Joined on 05-03-2004, 11:21 PM
    • Posts 39

    Hi,

    I am guessing the problem is caused by attempting to "multi-hop" NTLM credentials. The credential your users used to logon to your website (using integrated authentication) cannot be re-used to access another remote resource (which in this case is a network share). I am guessing that when you manually do the 2nd impersonation, you are creating a new credential (base on the info from the original credential) and hence it works (as the hop from your app to the network share is then treated as a first hop).

    As a test, try to logon to your app from the local server that is hosting the app. This then should work without the manual impersonation, as the credential is not being passed from the client machine to the web server, hence eliminating one hop.

    I am having the same problem, but in my case my web app was trying to invoke a web-service that requires integrated authentication.

    I was looking for info to solve my problem and found this link: http://www.velocityreviews.com/forums/t113829-call-to-webservice-doesnt-pass-in-credentials.html. You can get multi-hop NTLM credentials to work by setting up Keberos delegation, although this is something I have not tried as it is not an option in my organisation.

    I have a question about your manual impersonation method. One of the parametersis the password. Did you get that from the user input when they typed it into the login form? Or do you have someway to work it out??

    Cheers,

    Bernado

  • Re: Must Impersonate to access file on network-file-server, Why?? Please help I'm desperate

    08-03-2007, 12:38 AM
    • Loading...
    • Bernado
    • Joined on 05-03-2004, 11:21 PM
    • Posts 39

    Or you can try mapping a local drive to the share and see if that works as suggested: http://forums.asp.net/p/1141704/1839112.aspx

     

    :)

    Bernado

  • Re: Must Impersonate to access file on network-file-server, Why?? Please help I'm desperate

    08-03-2007, 6:50 AM
    • Loading...
    • deblendewim
    • Joined on 12-20-2006, 4:32 PM
    • Antwerp, Belgium
    • Posts 943

    Hi Bernado,

    Thanks for the reply, it clearified alot!

    About using mapped drives .... this should be for the ASPNET account then ..... I don't think that's possible after what I read here: http://www.thescripts.com/forum/thread287900.html 

    Well, it could be possible I guess, if you log-in with the aspnet account and lock it an let it run forever? (correct me if I'm wrong)

     

    For now, I'll just go with the extra impersonation. Kerebos is a solution but that implies some security issues so I can't deside that on my own.

    Also, The extra impersonation isn't that bad when it's molded into a class. Then whenever I need it, I can just do Using Impersonation ........ End Using.
    I found a nice class here: http://born2code.net/?page_id=45 Its a dutch site but the code is in english. (I transformed the class to a VB class, if anyone is interested, just privateMessage me)

     Kind regards,
    Wim

    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
  • Re: Must Impersonate to access file on network-file-server, Why?? Please help I'm desperate

    08-03-2007, 9:10 AM
    • Loading...
    • asp_guy
    • Joined on 08-02-2007, 7:56 PM
    • Posts 9

    Hey Wim,

    Sorry to hi-jack your thread here, but, I'm also running into a similar problem (http://forums.asp.net/p/1141704/1839783.aspx)

    I, too, don't understand why seeing "impersonation=true" in web.config does not work. However, as Bernado pointed out, perhaps it's because the authentication info is not delegated to remote machines? (By the way, I tried the suggestion of accessing my script from the local machine, and it still fails)

    Anyway, if I can't find an answer, I think I will just manually impersonate the user, like how you did. How did you retrieve the user's password to supply to your impersonateValidUser() routine?

    Thanks!

     

     

  • Re: Must Impersonate to access file on network-file-server, Why?? Please help I'm desperate

    08-03-2007, 9:53 AM
    • Loading...
    • Bernado
    • Joined on 05-03-2004, 11:21 PM
    • Posts 39

    asp_guy:
    How did you retrieve the user's password to supply to your impersonateValidUser() routine

    That's what I wanted to know too. I am guessing the password was input by the user in the login form (since Wim seems to have setup a form login as well).

    Wim, I just came across this thread that claims to have successfully got ASP.NET to map a drive: http://forums.asp.net/t/1141870.aspx . The code seems to be passing in a username and password when mapping the drive. Perhaps you can get the username/password as entered on the login form by the user and use it here.

    asp_guy, if you don't have a combination of form authentication & integrated authentication like Wim, perhaps you can setup a service account in your domain and use username/password of that account to map the drive.

  • Re: Must Impersonate to access file on network-file-server, Why?? Please help I'm desperate

    08-03-2007, 10:41 AM

    Why not try multi-authentication, i.e. authentication for network share differently then the actual intranet. Just suggesting this as other way. Even windows does that for your network share, despite you having permission on that resource from your credentials on Active Directory. That keeps the two as seperate entties.

     

    Although its a lot of heavy discussion on the top, It was very interesting reading through your stuffs and I can only appreciate your hard work and respect for sharing your ideas.

    Please Mark Post that helped you as answer, also include a summary of what solved the problem as it helps others in similar situations
  • Re: Must Impersonate to access file on network-file-server, Why?? Please help I'm desperate

    08-03-2007, 11:34 AM
    • Loading...
    • deblendewim
    • Joined on 12-20-2006, 4:32 PM
    • Antwerp, Belgium
    • Posts 943

    Hi all,

    Bernado:

    I have a question about your manual impersonation method. One of the parametersis the password. Did you get that from the user input when they typed it into the login form? Or do you have someway to work it out??

    Sorry, I completely looked over that question. I store the password in a Session Variable, I'm not so sure this is a safe way to go .... maybe I should encrypt it before storing it.
    Oh, and I do get it from the login-control (this is on my login page) (code behind):

    Protected Sub LoginControl_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles LoginControl.Authenticate
      If ValidateUser(Me.LoginControl.UserName, Me.LoginControl.Password) Then
    	e.Authenticated = True
    	Session("PassNT") = Me.LoginControl.Password
      Else
    	e.Authenticated = False
    	Me.LoginControl.FailureText = "You are not an Authenticated User. Please contact the Administrator."
      End If
    End Sub

     

    asp_guy:

    , too, don't understand why seeing "impersonation=true" in web.config does not work. However, as Bernado pointed out, perhaps it's because the authentication info is not delegated to remote machines? (By the way, I tried the suggestion of accessing my script from the local machine, and it still fails)

    Hi asp_guy, well, the perhaps can be commented out here, I'm quite sure he was right. After he said that, I did some more researching and came to this site: http://www.microsoft.com/technet/community/columns/insider/iisi0803.mspx . Here they say the following (well, it was a question about basic auth. versus windows auth. but the answer confirms Bernado's ...euhm sayings :)   ):

    "... However, when you authenticate to an IIS server using Integrated Windows, the result is type of logon called a “Network” logon. This kind of logon is far more secure than Basic, but the credentials cannot be forwarded to another server, unless Kerberos is used in the intranet. In the event that Kerberos is used (when properly configured), the user’s credentials can be delegated throughout the forest ..."

    About your code not working when trying it locally: Euhm, can you browse to the UNC- path through your Windows-Explorer? What is the error you are getting?

    (Btw, you can hy-jack my threads any time as long as you do it in a nice and friendly way Stick out tongue )

    Bernado:

    Wim, I just came across this thread that claims to have successfully got ASP.NET to map a drive: http://forums.asp.net/t/1141870.aspx .

    Bernado, thanks man!, I'll give that link a look, but I'm gonna do it next week because I'm tired and still must do some other tasks.

    naturehermit:

    Why not try multi-authentication, i.e. authentication for network share differently then the actual intranet. Just suggesting this as other way. Even windows does that for your network share, despite you having permission on that resource from your credentials on Active Directory. That keeps the two as seperate entties.

    Hi naturehermit,

    Do I understand you well? So, let's say, the user log's in, and then I can perform an extra authentication on the network share (example: \\myFileServer1\UseFullDocuments) at the start of the application. That would be sweet! If that was possible, maybe the programmatical impersonation wouldn't be necessary anymore. But, this is something new to me, I'm gonna check it out next week because I'm tired ;)

     

    Thanks all for sharing in this thread,
    I am once again a bit wiser :p
    Wim

    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
  • Re: Must Impersonate to access file on network-file-server, Why?? Please help I'm desperate

    08-03-2007, 11:44 AM

    Thats exactly what I mean.

    However storing password in a Session I am not sure its a good idea. There are many other ways to get the password, or use httpmodules during the authentication and set a ticket or something during authentication event and use that token, however it might be another tiring day to get that sorted. Perhaps you can look at that later.

    Thanks for considering the suggestion.

     

     

    Please Mark Post that helped you as answer, also include a summary of what solved the problem as it helps others in similar situations
Page 1 of 1 (11 items)
Microsoft Communities