Fix for Partially Trusted Clients using Windows Authentication

This week I'll be running a series covering fixes for WCF that may be hard to find and explaining the details behind each problem.

Connection sharing is a performance optimization to pool HTTP connections between multiple calls. Ordinarily, connections are not allowed to be shared if they use Windows authentication to identify the caller. WCF uses an option on HttpWebRequest called UnsafeAuthenticatedConnectionSharing to override this restriction. Instead, connection groups are established using the credential as part of the identifier of the group so that callers with the same credentials can share a connection.

A client with restricted permissions may not be allowed to set the UnsafeAuthenticatedConnectionSharing setting. This causes a security exception to be thrown when the setting is accessed, preventing the request from being made. You're encountering this problem if you see the following exception.

 System.Security.SecurityException: Request for the permission of type 'System.Net.WebPermission' failed.
System.Net.HttpWebRequest.set_UnsafeAuthenticatedConnectionSharing(Boolean value)
System.ServiceModel.Channels.HttpChannelFactory.GetConnectionGroupName(HttpWebRequest httpWebRequest, NetworkCredential credential, AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel, SecurityTokenContainer clientCertificateToken)
System.ServiceModel.Channels.HttpChannelFactory.GetWebRequest(EndpointAddress to, Uri via, NetworkCredential credential, TokenImpersonationLevel impersonationLevel, AuthenticationLevel authenticationLevel, SecurityTokenProviderContainer proxyTokenProvider, SecurityTokenContainer clientCertificateToken, TimeSpan timeout)

The fix catches the security exception so that the call can continue without the optimization to share connections. If an attempt to set UnsafeAuthenticatedConnectionSharing fails, then the channel factory will never try to set this setting again for later requests as well.

This fix is available for download from KB article 959546.