GProano's .Net BLog

.Net/CLR Security Discussion

ExecutionContext & WindowsIdentity.Name in new threads

In Whidbey we've introduced a new feature called the ExecutionContext which flows a good bit of information across threads - among this information is the current impersonation token on a thread.  Now when your code creates a new thread via Thread.Start, ThreadPool, Timer, BeginInvoke, BeginRead/Write - the new thread will have an impersonation token placed on it.  Typically, WindowsIdentity.GetCurrent().Name returns the name of the current user, but in Whidbey there's a little trick to this - if a thread has an impersonation token on it, it will return the user name of the primary token, not the impersonation token.  There's an easy way to get around it with the following function:

  static string GetUserName()
   {
   NTAccount acct = WindowsIdentity.GetCurrent().User.Translate(typeof(NTAccount)) as NTAccount ;
   if( acct != null )
    return acct.ToString() ;
   return String.Empty ;
   }

As you can see, GetCurrent() still returns the proper WindowsIdentity, but will need to convert it into an NTAccount to get the user name.  This code ends up looking pretty similar to what WindowsIdentity.User does!

As far as ExecutionContext goes, this is pretty much the tip of the iceberg.  In the coming days I will talk more about what it does, how to change its settings and also how you can use it with the new Hosting APIs.

Published Friday, March 04, 2005 3:39 PM by GProano
Filed under: ,

Comments

No Comments
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker