I have several intranet-only web sites written in ASP.NET MVC 5 and hosted on IIS7.
For these I want to enable impersonation when accessing the database.
I don't want the complete impersonation that lasts for the whole request - because I don't need it and because it is not supported in the integrated mode and requires suppressing the error.
The important note is that impersonation here is not related to security. I don't want to prevent anyone from accessing the web site (if they are on the company's network, that is already a granted permission).
Rather, I need to store the Windows user name in the database against certain actions for logging purposes only. If no Windows user name is available for logging, that is fine and the user must be able to proceed.
The code I'm going to be using will be
var identity = User.Identity as System.Security.Principal.WindowsIdentity;
if (identity != null && !identity.IsAnonymous)
{
using (var context = identity.Impersonate())
{
// access SQL Server who will get the user name from SUSER_SNAME()
}
}
The problem is that in order for IIS to pick up the Windows credentials, the anonymous access must be disabled, otherwise IIS will not even try to request credentials in some way or another.
This is a problem, because I want to keep the anonymous access.
Is it possible to somehow configure IIS or the application to let anonymous users in too?
Ideally this should be happening transparently, but if that is not possible, I will probably be happy with the browser displaying the username/password dialog, which the user would dismiss by clicking OK, which would provide blank username/password to IIS, which would allow them and map them to the anonymous situation (ish).
It is, however, not okay to request credentials from users whose browsers can provide Windows credentials automatically (IE does that by default, Firefox does that after changing a setting).
I have seen this .NET v1.1 era hack that involves reflection on private fields and this question on writing a custom HttpModule
- but it is said to be called after IIS completes its authentication business, which is too late, and I have no idea how to initiate an NTLM handshake from such a custom handler.