Implementing role-based security in a winform is the same as any other;
set the principal to something... at the simplest level see below(you
can do much more sophisticated thing if you create your own principal).
The advantage here is that a: it has runtime support built in (for the
attribute check), and b: any code (yours or 3rd party) can check the
same roles without needing to know about the specific implementation.
Note that VS2008 includes support for using the ASP.NET roles provider
inside a winform (via a web-service login).
For enforcing security on all the methods automatically (rather than
having to add the attribute) - one option would be PostSharp; it looks
like it would be trivial to add some code that simply does a Demand...
Marc
static void Main(string[] args)
{
string[] myRoles = {"GUEST", "USER"};
Thread.CurrentPrincipal = new GenericPrincipal(
new GenericIdentity("Fred"), myRoles);
UserMethod();
CheckManually();
AdminMethod();
}
[PrincipalPermission(SecurityAction.Demand, Role = "USER")]
static void UserMethod()
{
Console.WriteLine("User method");
}
static void CheckManually()
{
string role = "GUEST"; // dynamic...
bool isInRole = Thread.CurrentPrincipal.IsInRole(role);
// or to demand (throwing a suitable exception if not)
PrincipalPermission perm = new PrincipalPermission(null, role);
perm.Demand();
Console.WriteLine(isInRole);
}
[PrincipalPermission(SecurityAction.Demand, Role = "ADMIN")]
static void AdminMethod()
{
Console.WriteLine("Admin method");
}