Getting the current identity in WCF

Playing around with an ASP.NET-hosted WCF service today. While testing using the WCF Test Client I (unsurprisingly in retrospect) got a null reference exception when trying to access HttpContext.Current. This completely stuffed up my attempt to get the current identity from HttpContext.Current.User.Identity.

After a quick search I found the ServiceSecurityContext class in the System.ServiceModel namespace. This gives you the current identity using ServiceSecurityContext.Current.PrimaryIdentity (and also exposes the current WindowsIdentity).

Helpfully enough my code was well factored for once (to help with my unit testing/TDDing) and I only had to make the change in one place :)

Might be some more gotchas around this depending on what authentication mechanism you are using, but this was enough to get things working for me.

Comments