Setting the Thread.CurrentPrincipal inside an async method

Earlier this week I spent more time than I wanted for trying to figure out why I was losing the Thread.CurrentPrincipal value after having set it inside an async method. My history goes a lot like the one described here. But it took me sometime to find that website on Google, which was retrieving many results for web applications but very few for desktop. I also found similar problem described by this post.

In summary, I was working on authentication for a desktop application, using Open ID Connect and Identity Server. My calls to the user store are all based on WCF services, and I wanted to have the authentication done asynchronously to prevent my UI from locking up.

According to my first reference above, the Thread.CurrentPrincipal is associated with the current thread and the logical call context, and despite the async method executes in the same thread, any changes in the logical call context are discarded when the method completes.

At the end of the day, I “solved” it by not setting the Thread.CurrentPrincipal in the async method, but instead having the async method return the ClaimPrincipal and only set the Thread.CurrentPrincipal in the main thread, regular synchronous method. This sounds more like a workaround than a solutions, but in the Agile world I couldn’t spend endless time trying to make it work right. Maybe I will come back to this sometime in the future.

Here’s how I have it:

And in my client application, I have:


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.