Role Based Security & Limited Method Access in .NET Framework
We can use declarative role-based security demand to limit access to any given method. Couple things to watch out are: they can produce runtime exception error and they apply to entire method. In our example AdministratorsOnlyMethod() is protected with RBS
myPrincipal.Demand();
[PrincipalPermission(SecurityAction.Demand, Role = @"COMP\Administrators")]
[PrincipalPermission(SecurityAction.Demand, Name = @"COMP\User1", Role = @"COMP\Managers")]
[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
static void AdminOnlyMethod()
{
// Code can be run by Admin.
}
try
{ AdminOnlyMethod(); }
catch (System.Security.SecurityException ex)
{ MessageBox.Show("Your Account."); }
We can use imperative role-based security demand to limit access to any given method or any portion of it. This is an advantage over declarative RBS. PrincipalPermission has three different constructors
- PrincipalPermission(PermissionState) using a System.Security.Permissions.PermissionState object.
- PrincipalPermission(Name, Role) using Name and Role properties.
- PrincipalPermission(Name, Role, Authenticated) using Name, Role, and Authenticated.
myPrincipal.Demand();