RoleProvider Class
Here's part one of how I put together our "RoleProvider" class (whose name could conceivably change down the track), the usage of which I described here.
In this post I'll show you the class itself. Then in the next couple of days I'll post the helper classes that tell the Windows Forms and WPF data binding engine about the "extra properties" on the class.
Without further ado, the class:
public class RoleProvider { public RoleProvider() { WindowsIdentity id = WindowsIdentity.GetCurrent(); _principal = new WindowsPrincipal(id); _roles["Administrators"] = new string[] { "Domain Admins" }; } private Dictionary<string, IEnumerable<string>> _roles = new Dictionary<string, IEnumerable<string>>(); private WindowsPrincipal _principal; [Browsable(false)] public Dictionary<string, IEnumerable<string>> Roles { get { return _roles; } } public bool IsInRole(string role) { foreach (string grp in _roles[role]) { if (_principal.IsInRole(grp)) return true; } return false; } }
So there's not much to look at here. I'm picking up the currently-logged-in user with the WindowsIdentity.GetCurrent() call, and I've set up a dictionary of role names, each of which maps to a collection of strings (representing the AD groups that that role maps to).
For simplicity I've also added an "IsInRole" method, which iterates through all the groups defined in a role and returns true if the user is a member of at least one of them.
Next up I'll post the PropertyDescriptor descendant class which describes the boolean property for each role you add to the Roles dictionary.