casbin-net / casbin-aspnetcore

Casbin.NET integration middleware and sample code for ASP.NET Core
https://github.com/casbin/Casbin.NET
Apache License 2.0
64 stars 20 forks source link

how to use EFCore-Adapter together with casbin-aspnetcore #37

Closed pspeybro closed 2 years ago

pspeybro commented 2 years ago

Hi,

I was looking into using EFCore-Adapter to store policies in the same mysql database that my web application uses. However, the casbin-aspnetcore initialization only seems to allow a path to a csv file.

//Add Casbin Authorization services.AddCasbinAuthorization(options => { options.DefaultModelPath = ""; options.DefaultPolicyPath = ""; });

Is there a way to combine it with EFCore-Adapter?

Or should I in some way override the DefaultEnforcerProvider (which is used also in CoreServiceCollectionExtension.cs) Should I add an extra overload in CoreServiceCollectionExtension.cs as well to deal with a custom EnforcerProvider?

casbin-bot commented 2 years ago

@sagilio @xcaptain @huazhikui

sagilio commented 2 years ago

This issue will help you: https://github.com/casbin-net/casbin-aspnetcore/issues/17

I use TryAdd to add the DefaultEnforcerProvider, you can inject your own implementation above the AddCasbinAuthorization:

services.AddScope<IEnforcerProvider, MyEnforcerProvider>();
services.AddCasbinAuthorization(options =>
{
    options.DefaultModelPath = "";
    options.DefaultPolicyPath = "";
});
pspeybro commented 2 years ago

Thank you, we solved it with this solution: https://github.com/casbin-net/casbin-aspnetcore/issues/17#issuecomment-796658834

This also allowed us to add custom functions (with variable amount of parameters)

services.AddCasbinAuthorization(options => { options.PreferSubClaimType = "http://schemas.microsoft.com/identity/claims/objectidentifier"; options.DefaultModelPath = casbinModelPath; options.DefaultRequestTransformer = new CustomRequestTransformer(); options.DefaultEnforcerFactory = (p, m) => { var enf = new NetCasbin.Enforcer( casbinModelPath, new EFCoreAdapter<string, Policy, DbContext>(p.GetRequiredService())); enf.AddFunction("HasRole", new HasRoleFunc()); enf.AddFunction("HasFeature", new HasFeatureFunc()); return enf; };
});

public static bool HasRole(params object[] parameters){ ... }