Robert McLaws
Robert McLaws

Reputation: 2582

Filtering queries across $expands with WebApi2 OData

I have a WebApi 2.1 OData (v 5.1.1) service backed in Entity Framework 6.1. I'm trying to lock it down from a security standpoint, so that users can only query data that is theirs. I have everything working fine, until you get to the $expands option.

For the sake of this discussion, consider the following simplified data model:

public class Scenario
{
    public Guid Id { get; set; }
    public Guid CreatedById { get; set; }
}

public class Property
{
    public Guid Id { get; set }
    public Guid CreatedById { get; set; }
    public IQueryable<Scenario> Scenarios { get; set; }
}

When I call /Properties(guid'SOMEGUID')?$expand=Scenarios, I need to be able to make sure that only Scenarios where the CreatedById = CurrentUserId are returned. This needs to happen on the server-side and not in the client-side query.

WCF Data Services had QueryInterceptors that would handle this kind of situation... what is the equivalent in WebApi 2.1 OData?

Thanks!

Upvotes: 0

Views: 236

Answers (2)

Feng Zhao
Feng Zhao

Reputation: 2995

There are two ways to solve your problem if I understood your question correctly.

  1. Call the ApplyTo method of ODataQueryOptions on the IQueryable result
    public IQueryable<Property> Get(ODataQueryOptions queryOptions) { .... return queryOptions.ApplyTo(properties); }

  2. Add attribute Queryable on the GetData method and let WebAPI handles the query option
    [Queryable] public IQueryable<Property> Get() { ... return properties; }

Upvotes: -1

Javier
Javier

Reputation: 244

here's a gist with a sample on how can you implement this on your own: https://gist.github.com/anonymous/9237151

Based on my git, you can use a similar validator and implement your validation logic on a CanAcess method or similar. Let me know if this helps you.

We will have soon an official sample on http://aspnet.codeplex.com

Upvotes: 1

Related Questions