views:

841

answers:

4

I have an application that needs to hit the ActiveDirectory to get user permission/roles on startup of the app, and persist throughout.

I don't want to hit AD on every form to recheck the user's permissions, so I'd like the user's role and possibly other data on the logged-in user to be globally available on any form within the application, so I can properly hide functionality, buttons, etc. where necessary.

Something like:

if (UserProperties.Role == Roles.Admin)
{
    btnDelete.Visible = false;
}

What are the best practices for storing static user data in a windows app? Solutions such as a Singleton, or global variables may work, but I was trying to avoid these.

Is a User object that gets passed around to each form's contructor just as bad?

A: 

You can use the Profile provider from the asp.net in you Windows App. Check it out @ http://fredrik.nsquared2.com/viewpost.aspx?PostID=244&showfeedback=true

Hope it helps, Bruno Figueiredo http://www.brunofigueiredo.com

Bruno Shine
+2  A: 

Maybe my judgement is clouded by my frequent use of javascript, but I think that if you have something that is meant to be global, then using global variables is okay.

Global is bad when you are exposing things globally that shouldn't be. Global is okay if it is semantically correct for the intended use of the data.

Geoff
+5  A: 

Set Thread.CurrentPrincipal with either the WindowsPrincipal, a GenericPrincipal or your custom principal. Then, you can just call IsInRole:

if (Thread.CurrentPrincipal.IsInRole(Roles.Admin)) {
   btnDelete.Visible = false;
}
Mark Brackett
+1  A: 

Static data (or a singleton) seems fine for this if you want to scope the data to the application instance (or AppDomain).

However, given that you're talking about in effect caching a user's security credentials, you may want to carefully think about security loopholes. For example, what happens if the user leaves the application running for days? They could be performing operations under their days-old credentials rather than their most current credentials. Depending on what you're securing you might be better off checking credentials on demand or at least expiring the cached credentials periodically.

C. Dragon 76