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.
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.
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.
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.
OK, now let’s look at how we implemented this. Really the key code is the domain service on which runs on the server:
3: public class EmployeesDomainService : LinqToEntitiesDomainService<NORTHWNDEntities>
6: public IQueryable<Employee> GetEmployees()
8: foreach (var e in this.ObjectContext.Employees)
10: if (!this.ServiceContext.User.IsInRole("HRManagers"))
12: e.SSN = null;
14: else if (e.Title.Contains("Vice President"))
16: e.SSN = null;
19: return this.ObjectContext.Employees;
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