Implementing Role Based Security using C# - Now you have a WindowsPrincipal Object. So what?
(Page 3 of 4 )
The first thing you want to do is verify that the user is authenticated. Prior to accessing your application, the user should have entered a userid and password and been allowed into the system.
if (curIdentity.IsAuthenticated)
{
// User is authenticated, proceed
}
else
{
// Not authenticated, DO NOT allow access
}
Once you’re satisfied that a user is authenticated, you can now verify they belong to a role that is allowed to access a section of code and/or a particular feature. The work horse method you’ll use for this is called IsInRole(). To use IsInRole() you can pass in a Windows built-in role or a specific role that you may have created (a custom role or group). This is how you can restrict access to sections of code.
if (myPrincipal.IsInRole( @"myCompany\Employee_Role”)
{
// put code here
}
else
{
// User is not allowed to access code above
// do what you want here
}
Built in Role Member | Group |
AccountOperator | Account Operators |
Administrator | Administrators |
BackupOperator | Backup Operators |
Guest | Guests |
PowerUser | Power Users |
PrintOperator | Print Operators |
Replicator | Replicator |
SystemOperator | Server Operators |
User | Users |
You can use the Built in Roles like this:
If (myPrincipal.IsInRole( WindowsBuiltInRole.PowerUser )
// Then do something useful here
The use of Windows Built in Roles will vary from machine to machine. If you query for a role and it doesn’t exist, an exception will be thrown. Be prepared to catch the exception.
The PrincipalPermission Class
The PrincipalPermission Class enables you to demand that users of your code have been authenticated and/or belong to a specific role or group. The Declarative syntax is used and the security context is checked before a method is executed. You also can supply multiple security declarations for a method.
There are three properties that you MUST know:
- Authenticated - If true the caller must be authenticated.
- Name - The user's user name must match this string.
- Role - The user must at least be a member of this role.
In the example below the user needs to be either a member of the Sr_Managers or Managers group to execute the method:
[PrincipalPermissionAttribute(SecurityAction.Demand,
Name=@"myCompany\Sr_Managers ")][PrincipalPermissionAttribute(SecurityAction.Demand,
Name=@"myCompany\Managers ")]
Private void ManagersOnly()
{
//Do something for managers only
}
Remember, only one of the security declarations needs to be true in order for the method to execute.
Next: Design Principles to Implement Role Based Security >>
More C# Articles
More By Victor Stachura