-
Notifications
You must be signed in to change notification settings - Fork 20
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
EFCore persistence #17
Comments
Yes, you can implement a custom IEnforcerProvier like this: public class CustomEnforcerProvider : IEnforcerProvider
{
private readonly ICasbinModelProvider _modelProvider;
private readonly CasbinDbContext<Guid> _casbinDbContext;
private Enforcer _enforcer;
public CustomEnforcerProvider(ICasbinModelProvider modelProvider, CasbinDbContext<Guid> casbinDbContext)
{
_modelProvider = modelProvider;
_casbinDbContext = casbinDbContext;
}
public Enforcer GetEnforcer()
{
_enforcer ??= new Enforcer(_modelProvider.GetModel(), new EFCoreAdapter<Guid>(_casbinDbContext));
return _enforcer;
}
} And add service in Startup.cs like this: //Add Casbin Authorization
services.AddDbContext<CasbinDbContext<Guid>>(options => options.UseSqlite("Data Source=CasbinSample.db"));
services.AddScoped<IEnforcerProvider, CustomEnforcerProvider>();
services.AddCasbinAuthorization(options =>
{
options.PreferSubClaimType = ClaimTypes.Name;
options.DefaultModelPath = Path.Combine("CasbinConfigs", "basic_model.conf");
}); I think we can provide a quick way to configure EFCore Adapter later. |
Thanks,
Is there a reason not to use the factory method as above instead of using a custom enforcer provider? |
Because the EF Core Adapter needs a dbcontext which is a scope lifetime service. Use DefaultEnforcerFactory may can not get an IServiceProvider to create scope and resolve the dbcontext. |
I will try creating a custom enforcer provider as you suggest. (Although it is probably a good idea to make the changes to DefaultEnforcerFactory also as this is a natural place to customize this). |
Now services.AddDbContext<CasbinDbContext<Guid>>(options => options.UseSqlite("Data Source=CasbinSample.db"));
//Add Casbin Authorization
services.AddCasbinAuthorization(options =>
{
options.PreferSubClaimType = ClaimTypes.Name;
options.DefaultModelPath = Path.Combine("CasbinConfigs", "basic_model.conf");
options.DefaultEnforcerFactory = (p, m) =>
new Enforcer(m, new EFCoreAdapter<Guid>(p.GetRequiredService<CasbinDbContext<Guid>>()));
}); |
Excellent. Thank you. We need the casbin database updates to share transaction with updating other parts of the database, so we will check out the best way to handle the CasbinDbContext lifecycle |
Can we pin this somewhere in the wiki? I guess many of us wants to know how to use it with EF. |
@sagilio can we add this to README? |
@hsluoyz @VerdonTrigance |
Can the aspnet core middleware be configured to use EFCore instead of files to persist policy?
The text was updated successfully, but these errors were encountered: