When authorizing a client, how do I tell the difference between a connection with anonymous security and a connection with no security?

Anonymous security turns out to offer a surprising amount of protection even though you have no idea who the caller is. With anonymous message security, it's still possible to authenticate the server using the server's credentials and it's possible to protect messages using signing and encrypting. For that reason, some people will want to behave differently if clients are anonymously authenticated than if no security was applied.

Much of the information about client security is stored in the thread local ServiceSecurityContext. ServiceSecurityContext is actually about the remote endpoint, which is the client when running on the service and the service when running on the client. The simplest test is to look at whether a ServiceSecurityContext exists or not by checking ServiceSecurityContext.Current for null. If there's no ServiceSecurityContext, then you know that no security was applied. ServiceSecurityContext also has an IsAnonymous property that tells you whether information exists about the current client connection.

However, there are some cases where a ServiceSecurityContext is created even if there was no security for the client connection. If you have customized authorization through an extensibility point, such as installing a ServiceAuthorizationManager, then WCF may have created a ServiceSecurityContext despite there not actually being any security because it usually makes the authorization logic simpler. In that case, you could look at the tokens associated with the request and determine that some form of security was applied if any kind of token exists.

Next time: Ignoring Bad Requests