Search code examples
c#windowsiismodulewindows-server

How often does the Authenticate Event get called in an IIS Managed Module?


I am creating an IIS Managed module that will handle basic authentication against a SQL server backend datastore as opposed to the windows server accounts. I followed a Microsoft article on how to do this and used the following event to hook up the authentication request.

//Subscribe to the authenticate event to perform the authentication.
context.AuthenticateRequest += new EventHandler(this.AuthenticateUser);

In that authentication code, I access the database to check if the username and password provided match a user and if so I set the user principal.

//Create the user principal and associate it with the request.
context.User = new GenericPrincipal(new GenericIdentity(userName), null);

My question is, for every request AFTER this point, is the authenticateuser function called and the database is hit? I see that the basic authentication authorization header is passed for every request, even for jpgs etc, and I'm wondering does IIS know somehow that this user is authenticated and does not call the database or does the authenticate call get called on every request and instead of needing to ask for credentials, the browser is sending them over so it still does a database check every request?


Solution

  • For those who are wondering, I put a bunch of database logging all throughout the module events to check the order of how things went. Turns out the AuthenticateRequest event function is called for EVERY request to the server including images, javascript, css, json files, html, etc.

    Therefore if I do a database check in AuthenticateRequest then it will hit multiple times per page view. I implemented a caching system to get around this so the first time the AuthenticateRequest function is called it will hit the database and cache that user for a set amount of time before needing to call the database again.