Share via


Forcing reuse of connections when doing Windows Authentication

When doing authentication, HttpWebRequest manages connections differently, depending on the authentication mode being used. If it uses Windows Integrated Authentication, it will close the connection after every request completes. The reasons for this are complex, and I wont go into them at this point.

However, there are cases where you dont want this to happen. For example, imagine that you have a 3-tier architecture, where the client is talking to an asp.net application, which in turn is hitting a backend webserver. The asp.net webapplication (henceforth called the MiddleTier) is using HttpWebRequest to talk to the back-end, and the back-end is secured by Windows Integrated Authentication.

If the middle-tier web application ends up getting a lot of requests, it will inturn issue a lot of requests to the back-end. The default behavior of webrequest is to create a new connection for each request, and over time, the middle-tier might end up running out of wildcard TCP ports, causing the HttpWebRequest to fail with a "Unable to connect to the remote server" exception.

To mitigate this, you want to use a property on the webrequest called UnsafeAuthenticatedConnectionSharing . Setting this property will cause HttpWebRequest to reuse authenticated connections (making sure that it honors ServicePoint.ConnectionLimit).

Security Note: You dont want to use this property lightly. It has security consequences.