I've got a simple WPF 4.0 app that currently has no concept of user security. I need to add some very simple username/password based security and access the credentials in just a couple of spots, and want to utilize Thread.CurrentPrincipal. I am wondering what the ramifications of simply changing this property are? Will it affect the .Net Framework or limit the application in any way? Or, as I suspect, will it have zero effect until I utilize it elsewhere in my app?
+1
A:
You should be fine changing Thread.CurrentPrincipal
, as it is a standard mechanism for using principals within .Net, especially as you have a WPF application.
Be careful when dealing with ThreadPool
threads though - don't change it on a thread from the thread pool unless you also set it back to its original value before you let the thread die. Thread pool threads can be reused and are not "reset", so any principal you set on the thread will remain when/if the thread is obtained again from the thread pool - you don't know what could obtain this thread.
This is actually how Windows and IIS deal with authentication with .Net. If you call
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
in your code, the currently logged-on user will be populated into Thread.CurrentPrincipal
for you.
adrianbanks
2010-05-27 20:34:19
"In the .NET Framework version 2.0 [and higher, implicitly], the Thread.CurrentPrincipal property value is propagated to worker threads queued using the QueueUserWorkItem method. In earlier versions, the principal information is not propagated." (from http://msdn.microsoft.com/en-us/library/kbf0f1ct.aspx)
Jeff Sternal
2010-05-27 20:36:35
With regards to v2.0 and higher propagating the CurrentPrincipal, does this imply I can in fact change the value in a threadpool thread without worry?
BrettRobi
2010-05-27 20:43:46
@BrettRobi: It does look like the principal is set on `ThreadPool` threads when a work item is queued, so it does get reset (ie. it should be ok). What I've said does apply to other properties though (eg. `Thread.CurrentCulture`).
adrianbanks
2010-05-27 20:47:19