WebApi OData for user security on your resource

I have some objects that have data that should be available only to some users.

public class Foo { public virtual Bar { get; set; } ... } public class Bar { public string Secret { get; set; } ... } 

For example, Bar.Secret should be available only to UserA , but not to UserB . I could have something like this:

 public class BarsController : ODataController { [EnableQuery] public IHttpActionResult Get() { if (User.Identity.Name != "UserA") return Unauthorized(); return _db.Bars(); } } 

Also, this is a poor implementation. It does not apply to this controller:

 public class FoosController : ODataController { [EnableQuery] public IHttpActionResult Get() { return _db.Foos(); } } 

What can be called with /odata/Foos?$expand=Bars , and then I could look at Bar.Secret . I can't just turn off $expand on Foo because this request is completely finished for UserA , and is also necessary.

Is there a way to make OData test queries against some predicate that includes the requested objects.

Sort of

 public class SecureEnableQueryAttribute : EnableQueryAttribute { public bool ValidateResult(IEnumerable<T> entities) { return entities.All(x => x.Secret == UserA.Secret); } } 
+5
source share
1 answer

You can check query parameters before query execution and fail if the user is not allowed to request data. To do this, output EnableQueryAttribute and override ValidateQuery .

 public class SecureEnableQueryAttribute : EnableQueryAttribute { public virtual void ValidateQuery(HttpRequestMessage request, ODataQueryOptions queryOptions) { base.ValidateQuery(request, queryOptions); // Insert custom logic, possibly looking at queryOptions.SelectExpand // or queryOptions.RawValues. } } 
0
source

Source: https://habr.com/ru/post/1232729/


All Articles