Michael O'Dea-Jones' Blog

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

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

 

Jamie said:

Thank you - was looking for a quick solution for this.

January 30, 2009 6:52 AM

Leave a Comment

(required) 
(optional)
(required) 
Submit

News

Michael is a .Net Developer who enjoys creating software and doing database work too.

Tags

No tags have been created or used yet.