2

I'm writing a Rest API Framework, I'd like to create a db authorization context. The context takes in a role resolver and uses that to filter the default set. Base on a set of rules.

In my First Attempt I thought maybe I could apply default filters to the entity sets to prohibit access to certain resources

public class AuthorizationContext : DbContext
{
    protected IConstraintResolver _constraintResolver;
    public AuthorizationContext(IConstraintResolver constraintResolver)
    {
        this._constraintResolver = constraintResolver;

    }

    public override DbSet<TEntity> Set<TEntity>()
    {
        var defaultSet = base.Set<TEntity>();

        var constraints = this._constraintResolver.GetConstraintsForTypeByRole<TEntity>();

        var filteredSet = base.Set<TEntity>().AsQueryable();

        foreach (var constraint in constraints)
        {
            filteredSet = filteredSet.Where(constraint);
        }
        //how do I apply this back to the innerQueryable
        return filteredSet;
    }
}

but this does not compile I because I cannot transform my Queryable back to a filteredDBSet.

I found a few articles on different ways to Secure data in EF-Core, but using this method would require, is not how I want to secure my data.

  1. I want my context to implicitly secure data based off the role (so that any user using the context will not have to worry about wraping their queries to check for authorization.)
  2. A lot of additional configuration for the user

I have a function which already generates my Expressions based on the metadata of the SQL. My issue is applying to filter to the DBSets.

Assuming you are given an Expression<TEntity, Bool> How can I secure my context so that a user can only access or modify the data I've decided?

johnny 5
  • 19,893
  • 50
  • 121
  • 195

1 Answers1

2

Expression<TEntity, bool> sounds like a good candidate for EF Core 2.0 Global Query Filter.

You can set it for specific entity:

modelBuilder.Entity<SomeEntity>().HasQueryFilter(expression);

or for multiple entities based on some criteria - examples are EF-Core 2.0 Filter all queries (trying to achieve soft delete) and ef core 2 apply HasQueryFilter for all entity.

Please note that currently the global query filters have some limitations and special requirements to be rooted to the DbContext derived class if they need to be dynamic etc. (EF Core: Soft delete with shadow properties and query filters). I'm pretty sure they will be improved over the time, but it's good to check if the current functionality can serve your needs.

Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343