Michael O'Dea-Jones

Why is Thread.CurrentPrincipal.Identity.Name empty?

I am trying to get an audit trail going and want to record the user who created and modified the record in the database. I'm developing a .Net Windows Forms Application and assumed that the Current Principal's Identity was being set magically to the current user's identity. That's where my assumption was wrong. Apparently you have to set the Principal yourself. Here is the code that you can use to set the Application thread's Principal to the current User:

Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

I added this line of code to the Main method in the Program class:

static class Program

{

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main()

{

Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new ProcessForm());

}

}

For custom security situations you can create your own Generic Identity and set the current thread's Identity to it:

string[] Roles = { "Employee" };

GenericIdentity Identity = new GenericIdentity("Michael");

GenericPrincipal Principal = new GenericPrincipal(Identity, Roles);

Thread.CurrentPrincipal = Principal;

Published Tuesday, July 29, 2008 11:33 AM by michael@wardyit.com

Comments

No Comments
Anonymous comments are disabled