Sdílet prostřednictvím


Getting the Client Identity

How does my service know the identity of one of the connecting clients?

I'm going to focus this answer on obtaining a Windows identity since it's easier to write if I've just picked a single kind of identity. You can use whatever identity mechanism you want and the same technique will work. The only difference is that Windows identities get their own specially named property. A Windows identity is available on the service at least when Windows based message security has been enabled on the binding. I picked Windows identities because that's typically what is enabled by default. The WSHttp and NetTcp bindings have Windows security on by default. Other bindings, or custom bindings using an appropriate binding element, can enable Windows security if available.

If you are familiar with .NET security programming, then you may have first started by trying to use Thread.CurrentPrincipal to get the identity. CurrentPrincipal sometimes works (it requires enabling some specific settings) but there's a different standard mechanism for obtaining the calling client identity in WCF that is more expressive. The ServiceSecurityContext contains the Windows identity of the calling party when it is known in the obviously named WindowsIdentity property. The ServiceSecurityContext exists on both the client and server. The identity in this context always represents the remote identity. Like other contexts in WCF and CurrentPrincipal, the ServiceSecurityContext is bound to a thread, so you can access the relevant instance for this processing thread through ServiceSecurityContext.Current.

The ServiceSecurityContext has a wealth of other information that you can use. In addition to the remote identity, the most useful bit of information to make note of is the AuthorizationContext. The AuthorizationContext has the claim sets that WCF created for the current caller from the tokens in the message, an instance of the current IPrincipal in Properties["Principal"], and a list of all of the identities from the various security layers being used in Properties["Identities"].

Next time: Mapping to a VDir