Can anyone please explain the function of the lines below:
WindowsIdentity wId = (WindowsIdentity)HttpContext.Current.User.Identity;
WindowsImpersonationContext wIdCon = wId.Impersonate();
That is used on a POST method with IIS basic authentication and works fine. If however the IIS authentication is set to windows the above no longer works.
There is simply way too much code to dump for an example.
The call to
Impersonate()
makes IIS pretend to be the requesting user from that point on. This is useful for a number of reasons, chiefly that the subsequent code will only work if the requesting user is not denied access.This works for basic because the website is given the username and password and can therefore login as the user. Windows authentication is failing becuase it uses kerberos and is only given a ticket refering the the user - not the users password.
To get Windows authentication to work, you need to allow the website account (the one that is the app pool identity for your application) to impersonation users. This is done in the delegation tab of their account in Active Directory.
If they don't have a delegation tab, you first need to add an SPN (a Service Principal Name). The SPN allow clients to know which account is running the website and therefore how to encrypt to kerberos ticket such that the website can open it. It's all a way of allowing client and server to talk without every telling each other their passwords as long as they both trust a 3rd party (the AD server in the standard MS implementation).
This is all part of a common problem known as kerberos double hop. it all stems from the fact that Kerberos from the client to the website works (the website knows enough about the client users credentials to serve pages etc) but the 2nd hop from the website to the resource that requires the web users credentials is not being given them as the website account is not allowed to. For more info see understanding-kerberos-double-hop on msdn
EDIT:
Try running
setspn /q http/machine_name_or_fqdn
e.g.Which user are these spn's set against? IIS needs to have the appPool for the website running as same user as the SPN.
Once you've confirmed that, I'd suggest using the fiddler tool to check what is passing between the client and the server - confirm that is getting a 401 error response (i.e. you need to authenticate) and immediately retrying with the request having a valid kerberos header.
Once you've got the client to server talking via kerberos, you need to ensure the appPool account has been set in AD as allowed to delegate on behalf of users.