Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API OData Security per Entity

Background:
I have a very large OData model that is currently using WCF Data Services (OData) to expose it. However, Microsoft has stated that WCF Data Services is dead and that Web API OData is the way they will be going.

So I am researching ways to get Web API OData to work as well as WCF Data Services.

Problem Setup:
Some parts of the model do not need to be secured but some do. For example, the Customers list needs security to restrict who can read it, but I have other lists, like the list of Products, that any one can view.

The Customers entity has many many associations that can reach it. If you count 2+ level associations, the are many hundreds of ways that Customers can be reached (via associations). For example Prodcuts.First().Orders.First().Customer. Since Customers are the core of my system, you can start with most any entity and eventually associate your way to the Customers list.

WCF Data Services has a way for me to put security on a specific entity via a method like this:

[QueryInterceptor("Customers")] public Expression<Func<Customer, bool>> CheckCustomerAccess() {      return DoesCurrentUserHaveAccessToCustomers(); } 

As I look at Web API OData, I am not seeing anything like this. Plus I am very concerned because the controllers I am making don't seem to get called when an association is followed. (Meaning I can't put security in the CustomersController.)

I am worried that I will have to try to somehow enumerate all the ways that associations can some how get to customers and put security on each one.

Question:
Is there a way to put security on a specific entity in Web API OData? (Without having to enumerate all the associations that could somehow expand down to that entity?)

like image 759
Vaccano Avatar asked Jul 27 '14 14:07

Vaccano


People also ask

Is OData obsolete?

Custom V2 OData queries will be deprecated March 9, 2021.

Is OData secure?

The fact is that using OData is orthogonal to authentication and authorization. That is to say, you may secure an OData API in any way you can secure a generic RESTful API.

What is OData in Web API with example?

The Open Data Protocol (OData) is a data access protocol for the web. OData provides a uniform way to query and manipulate data sets through CRUD operations (create, read, update, and delete). ASP.NET Web API supports both v3 and v4 of the protocol.


2 Answers

UPDATE: At this point in time I would recommend that you follow the solution posted by vaccano, which is based on input from the OData team.

What you need to do is to create a new Attribute inheriting from EnableQueryAttribute for OData 4 (or QuerableAttribute depending on which version of Web API\OData you are talking with) and override the ValidateQuery (its the same method as when inheriting from QuerableAttribute) to check for the existence of a suitable SelectExpand attribute.

To setup a new fresh project to test this do the following:

  1. Create a new ASP.Net project with Web API 2
  2. Create your entity framework data context.
  3. Add a new "Web API 2 OData Controller ..." controller.
  4. In the WebApiConfigRegister(...) method add the below:

Code:

ODataConventionModelBuilder builder = new ODataConventionModelBuilder();  builder.EntitySet<Customer>("Customers"); builder.EntitySet<Order>("Orders"); builder.EntitySet<OrderDetail>("OrderDetails");  config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());  //config.AddODataQueryFilter(); config.AddODataQueryFilter(new SecureAccessAttribute()); 

In the above, Customer, Order and OrderDetail are my entity framework entities. The config.AddODataQueryFilter(new SecureAccessAttribute()) registers my SecureAccessAttribute for use.

  1. SecureAccessAttribute is implemented as below:

Code:

public class SecureAccessAttribute : EnableQueryAttribute {     public override void ValidateQuery(HttpRequestMessage request, ODataQueryOptions queryOptions)     {         if(queryOptions.SelectExpand != null             && queryOptions.SelectExpand.RawExpand != null             && queryOptions.SelectExpand.RawExpand.Contains("Orders"))         {             //Check here if user is allowed to view orders.             throw new InvalidOperationException();         }          base.ValidateQuery(request, queryOptions);     } } 

Please note that I allow access to the Customers controller, but I limit access to Orders. The only Controller I have implemented is the one below:

public class CustomersController : ODataController {     private Entities db = new Entities();      [SecureAccess(MaxExpansionDepth=2)]     public IQueryable<Customer> GetCustomers()     {         return db.Customers;     }      // GET: odata/Customers(5)     [EnableQuery]     public SingleResult<Customer> GetCustomer([FromODataUri] int key)     {         return SingleResult.Create(db.Customers.Where(customer => customer.Id == key));     } } 
  1. Apply the attribute in ALL actions that you want to secure. It works exactly as the EnableQueryAttribute. A complete sample (including Nuget packages end everything, making this a 50Mb download) can be found here: http://1drv.ms/1zRmmVj

I just want to also comment a bit on some other solutions:

  1. Leyenda's solution does not work simply because it is the other way around, but otherwise was super close! The truth is that the builder will look in the entity framework to expand properties and will not hit the Customers controller at all! I do not even have one, and if you remove the security attribute, it will still retrieve the orders just fine if you add the expand command to your query.
  2. Setting the model builder will prohibit access to the entities you removed globally and from everyone, so it is not a good solution.
  3. Feng Zhao's solution could work, but you would have to manually remove the items you wanted to secure in every query, everywhere, which is not a good solution.
like image 108
Savvas Kleanthous Avatar answered Oct 06 '22 01:10

Savvas Kleanthous


I got this answer when I asked the Web API OData team. It seems very similar to the answer I accepted, but it uses an IAuthorizationFilter.

In interest of completeness I thought I would post it here:


For entity set or navigation property appears in the path, we could define a message handler or an authorization filter, and in that check the target entity set requested by the user. E.g., some code snippet:

public class CustomAuthorizationFilter : IAuthorizationFilter {     public bool AllowMultiple { get { return false; } }      public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(         HttpActionContext actionContext,         CancellationToken cancellationToken,         Func<Task<HttpResponseMessage>> continuation)     {         // check the auth         var request = actionContext.Request;         var odataPath = request.ODataProperties().Path;         if (odataPath != null && odataPath.NavigationSource != null &&             odataPath.NavigationSource.Name == "Products")         {             // only allow admin access             IEnumerable<string> users;             request.Headers.TryGetValues("user", out users);             if (users == null || users.FirstOrDefault() != "admin")             {                 throw new HttpResponseException(HttpStatusCode.Unauthorized);             }         }          return continuation();     } }  public static class WebApiConfig {     public static void Register(HttpConfiguration config)     {         config.Filters.Add(new CustomAuthorizationFilter()); 

For $expand authorization in query option, a sample.

Or create per user or per group edm model. A sample.

like image 27
Vaccano Avatar answered Oct 05 '22 23:10

Vaccano