Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Impersonation in ASP.NET web application does not work when running on IIS

I am working on ASP.NET 4.0 MVC3 web application that works in intranet environment. The application makes use of Windows authentication. Its application pool is run by domain user that has spn set on a domain controller. Authentication works using Kerberos (on IE and Firefox after some additional configuration).

Now I want to upload files to sharepoint, but it's important for me to upload the file as the user currently logged in into the application (so the file is created on Sharepoint with his/her credentials).

I have the following code in ResourceExists(Uri uri) function:

'...
    Dim identity As System.Security.Principal.WindowsIdentity = HttpContext.User.Identity
    Dim impersonationContext = identity.Impersonate()
    response = request.GetResponse()
    impersonationContext.Undo()
'...

This works when running locally, but when I deploy to the server I get the exception:

System.Net.WebException: The remote server returned an error: (401) Unauthorized.\r\n   at WebDav.WebDavClient.ResourceExists(Uri uri)\r\n   at Website.Website.WebdavController.Upload(HttpPostedFileBase file, UploadViewModel vm)

I read something about passing on the credentials, that is not possible with NTLM, but I am sure I am using Kerberos (I checked the headers with wireshark and fiddler) and I see the following:

Authorization: Negotiate YIIFpQYGKwYBBQUCoIIFmTCCBZWgJDAiBgkqhkiC9x...

Any ideas why the impersonation does not work when running on the IIS server?

like image 926
Michal B. Avatar asked Jun 18 '12 08:06

Michal B.


2 Answers

I found the answer here:

http://support.microsoft.com/kb/810572

"Kerberos does not work in a load-balanced architecture and IIS drops back to NTLM authentication. Because you cannot use NTLM for delegation, any applications or services that require delegation do not work. For more information, click the following article number to view the article in the Microsoft"

And that was exactly the case. I tried now with another machine that is not load-balanced and it works.

The only thing that still surprises me is that ImpersonationLevel of the identity is still Impersonate not Delegate...

like image 101
Michal B. Avatar answered Nov 15 '22 06:11

Michal B.


After setting <identity impersonate="true"/> in your web.config try the following:

using (((WindowsIdentity)User.Identity).Impersonate())
using (var client = new WebClient { Credentials = CredentialCache.DefaultNetworkCredentials })
{
    string result = client.DownloadString("http://sharepoint");
}
like image 39
Darin Dimitrov Avatar answered Nov 15 '22 05:11

Darin Dimitrov