Field Level Access with RIA Services

There are lots of reason you may need to customize the access to given fields within an entity.  For example, HIPPA compliance requires that some data not be exposed to only employees with a need to know.   It is often not sufficient to just NOT show the data in the Silverlight client, you need to not even send it over the wire. 

This example works with Silverlight 4\RIA Services Beta and Visual Studio 2010 Beta2

I built a very simple RIA Services + Silverlight 4 example to show how this could be done.   First, let’s run the app, then we can look at how we built it.

The first thing to notice is when we run it, no users are logged in, so we get no access to the data at all. 

image

First, let’s log in as a Rocky, who is a jr. employee at our company.  He should NOT have access to the social security numbers of employees, but the other information is good for him to be able to access.

image

As you can see, no SSNs are displayed.

Now, let’s log in as Billy, who is our HR Manager…  As you can see, Billy has a need to know what the SSN is for most employees, so those are visible to him.  But notice, even he can not see VP level personal information. 

image

OK, now let’s look at how we implemented this.   Really the key code is the domain service on which runs on the server:

   1:     [RequiresAuthentication]
  2:     [EnableClientAccess()]
  3:     public class EmployeesDomainService : LinqToEntitiesDomainService<NORTHWNDEntities>
  4:     {
  5: 
  6:         public IQueryable<Employee> GetEmployees()
  7:         {
  8:             foreach (var e in this.ObjectContext.Employees)
  9:             {
 10:                 if (!this.ServiceContext.User.IsInRole("HRManagers"))
 11:                 {
 12:                     e.SSN = null;
 13:                 }
 14:                 else if (e.Title.Contains("Vice President"))
 15:                 {
 16:                     e.SSN = null;
 17:                 }
 18:             }
 19:             return this.ObjectContext.Employees;
 20:         }
 21: 
 22: 

In line 1, we mark this services are only accessible to users that are logged in.

In line 10, we are making sure that only the user making the request is in the role that enables them to have access to the SSN, if not, we null it out.

In line 14, we have a (lame) example to show accessing data on the entity to decide if the user should have access.  In this case, even the HRManager can’t access the VP’s SSN. 

 

Some notes on running the app:

  • Download the source code
  • Billy and Rocky’s passwords are “password1!”
  • Be sure the refresh the page after logging in or out
  • You can customize the roles by using the IIS Admin tool or the ASP.NET configuration properties on the Web solution

 

Enjoy!