WCF Data Services – Entity Set Access Rules
February 21, 2011 Leave a comment
WCF Data Services provides easy set up for your services. An example of this is how easy it is to configure allowed operations on entity sets. For this example, we have the following entity model:
* Note that I am not a fan of capturing and storing username and passwords. I’d rather let someone else do this so I don’t have to. I’ll post something on this topic in the coming weeks. *
If you generate a WCF Data Service, you’ll end up with:
public class UserService : DataService<coreentities>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
}
So what does this service do? Nothing really? By default, WCF Data Services locks down all entities so since we haven’t explicitly set what operations are allowed on the entities then we can’t do anything. However, adding the common line
config.SetEntitySetAccessRule("Users", EntitySetRights.All);
changes this picture so that any operation (CRUD for instance) is now allowed. However, there’s pretty granular control available. Changing the line above to
config.SetEntitySetAccessRule("Users", EntitySetRights.ReadSingle
| EntitySetRights.WriteAppend
| EntitySetRights.WriteMerge
| EntitySetRights.WriteReplace);
now allows retrieving a single user, creating a new user, and updating an existing user. Retrieving multiple users is not allowed. Combine this with QueryInterceptors and ChangeInterceptors and it becomes very easy to return only the logged in users user record and limits them to only update their own record.
[QueryInterceptor("Users")]
public Expression<func><user , Boolean>> OnQueryTasks()
{
return result => result.Username.Equals(HttpContext.Current.User.Identity.Name);
}
There are a lot of different options available and thankfully the configuration model has been greatly simplified. The days of configuring pure WCF will not be missed…at all.