Blogger :
Scott on Writing
All posts :
All posts by Scott on Writing
Category :
ASP.NET
Blogged date : 2006 Oct 04
In my Limiting Data Modification Functionality Based on the User (C# version) tutorial, I show how to adjust the functionality at the presentation layer based on the “currently logged on user.” (The demo doesn't actually setup the membership and roles systems, and rather allows the visitor to pick who they are logged on as from a drop-down list. See my Examining ASP.NET 2.0's Membership, Roles, and Profile article series for more information.)
One question I have received more than a couple of times is how to extend the permission-based business rules down into the Business Logic Layer and/or Data Access Layer. That is, how can I configure my BLL so that if my presentation layer has a bug or whatever, a person who is not authorized to, say, delete a record, is forbidden from doing so.
There are a couple of ways. One way is to add the logic programmatically to your BLL or DAL. You can access information about the currently logged in user in these layers using the Membership or Roles classes in the .NET Framework, like so:
1 public bool AddProduct(...)
2 {
3 if (!Roles.IsUserInRole("Administrator"))
4 throw new System.Security.SecurityException("You do not have permission to add a new product to the system.");
5
6 ...
Alternatively, you can specify authorization rules using PrinciplePermissionAttributes, as discussed by Scott Guthrie in his blog entry Adding Authorization Rules to Business and Data Layers using PrincipalPermissionAttributes.
With Scott Guthrie's approach, your BLL or DAL's code would include attributes defining the permissions required.
using System;
using System.Security.Permissions;
[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
public class EmployeeManager
{
[PrincipalPermission(SecurityAction.Demand, Role = "Manager")]
public Employee LookupEmployee(int employeeID)
{
// todo
}
[PrincipalPermission(SecurityAction.Demand, Role = "HR")]
public void AddEmployee(Employee e)
{
// todo
}
}
The benefits of PrincipalPermissionAttribute, as noted by Scott, are:
“The PrincipalPermissionAttribute isn't tied to any specific authentication mode. It will work with Forms Authentication, Windows Authentication, Passport Authentication, or any custom authentication mode you want to invent. It will also work with any Role implementation I might use (so if you build or plug-in your own Role Provider in ASP.NET it will just work).
“The PrincipalPermissionAttribute type is implemented in the standard CLR mscorlib assembly that all .NET projects compile against. So it isn't ASP.NET specific, and can be used within any application type (including Windows and Console applications). In addition to making it more generically useful, this makes it easier to unit-test business/data libraries built with it.”