In ASP.NET is there an event fired on a Windows Au

2019-07-04 16:12发布

问题:

I am building a .NET 4.0, ASP.NET MVC 3 intranet application that runs on IIS 7.5 in integrated mode. Windows Authentication is used to govern access to the website. The Windows Authentication module is enabled and all other auth modules are disabled.

Currently when a user provides improper credentials, the Windows Authentication module correctly rejects the credentials and re-displays a login prompt. It does so 3 times, after which a standard .NET 401 Unauthorized Access page is shown. This is expected and desirable.

My goal: I would like to be able to log the details of the failed authentication attempt to my own custom event log. Particularly, to capture the user name that was used in the log in attempt. (I'll accept that capturing the password is not likely to be possible for security reasons.)

Is my goal possible?

I have already built a working an IHttpModule module and added it as an event handler to the WindowsAuthenticationModule, like this:

myWindowsAuthenticationModule.Authenticate += WindowsAuthentication_Authenticate;

But my code does not get called in the case of a failed log in attempt, presumably because WindowsAuthenticationModule has already decided that the log in is failed and so there is no point calling my module. My module does get called after a successful log in attempt, and so I am certain that my event handler is properly set up.

To the best of my knowledge, the WindowsAuthenticationModule does not expose an event that is fired when authentication fails, so that option is out.

Any ideas? Or am I barking up a tree that has no solution?

回答1:

I was looking at the same issue, and looks like there is no events for windows authentication, even that Authenticate event is common for forms and windows.

But I found a solution to this!

http://www.codeproject.com/Articles/11202/Redirecting-to-custom-401-page-when-quot-Access-de

UPDATE

From original article

protected void Application_EndRequest(Object sender, EventArgs e)
{ 
 HttpContext context = HttpContext.Current;
 if (context.Response.Status.Substring(0,3).Equals("401"))
 {
    if(User.Identity.IsAuthenticated)
    {
        // this means user is authenticated, but 401 still returned
        // which means no access to page or whatever you are trying to access?
    }
 } 
}

UPDATE2

I also found out that this solution doesn't work in all cases. I was testing in different environments, so was working for me, but not for others.

By default IIS will not even run this piece of code and just return it's own error page, what you want to do is tell IIS to let app handle errors.

<httpErrors existingResponse="PassThrough">
</httpErrors>

Now, with that said, IIS won't return any more of custom errors and you will need to handle them in application, ie. not only 401, but 403, 405, etc