casbin-net / casbin-aspnetcore Goto Github PK
View Code? Open in Web Editor NEWCasbin.NET integration middleware and sample code for ASP.NET Core
Home Page: https://github.com/casbin/Casbin.NET
License: Apache License 2.0
Casbin.NET integration middleware and sample code for ASP.NET Core
Home Page: https://github.com/casbin/Casbin.NET
License: Apache License 2.0
After upgrading to Casbin.AspNetCore v0.2.0 It seems the overrides specified in services.AddCasbinAuthorization() does not have an effect.
Using the code below I have not been able to verify that the DefaultEnforcerFactory
lambda is called, or that the VerjiRbacTenantRequestTransformer()
is ever called.
services.AddCasbinAuthorization(options =>
{
options.PreferSubClaimType = "sub";
options.DefaultModelPath = Path.Combine(@"AccessControl\CasbinConfigs", "basic_rest_domain_model.conf");
options.DefaultPolicyPath = Path.Combine(@"AccessControl\CasbinConfigs", "basic_rest_domain_policy.csv");
// Comment line below to use the default BasicRequestTransformer
// Note: Commenting the line means that the action methods MUST have [CasbinAuthorize()] attribute which explicitly specifies obj and policy. Otherwise authorization will be denied
options.DefaultRequestTransformer = new VerjiRbacTenantRequestTransformer();
options.DefaultEnforcerFactory = (svc, model) =>
{
var context = svc.GetRequiredService<VerjiCasbinDbContext>();
var adapter = new EFCoreAdapter<Guid>(context);
return new Enforcer(model, adapter);
};
});
Did anything change in v0.2.0 so this must be done differently?
PS: I'm consuming the packages from nuget.org (and not myget.org/casbin)
I cloned and ran the sample. After some experiments, I found that in basic_policy.csv, GET
works but Get
not work.
GET
or POST
, etc. Could you please explain a little why in policy.csv
the action syntax must be all upper case? Is it related to some http specification? Is it implement dependent(is the behaviour related to operation system/browser versions)?A more lightweight DI extension method without authorization should be seperately provided.
Casbin.NET may act as a pure service for resource permission storage. In this scenario, people focus on the permissions they have ,not challenging the authorization.
We can provide extension method such as AddCasbinCore
and AddCasbinAuthorization
to meet these aspects of needs.
AddCasbinCore
serves basic Casbin.Net as a library,providing an ability to use basic Enforcer
and Management API
,while AddCasbinAuthorization
focus on Permission authorize middleware registration.
The latest version is 0.1.0-build.71.master.51c2fd0
, it's too long and unfriendly. We should use semantic-versioning.
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?
What is the intended lifecycle for enforcer? And how can we ensure enforcer use "fresh data" when:
Initially we tried using RedisWatcher approach, but it had limitations so we tried developing a different approach, also using Redis to notify processes to update casbin.
However we are not able to get this working (seem to be caching/remembering the old casbin_rules). So before digging more into this it would be really helpful if you could clarify:
If both of these objects are made fresh for each request, changes to the database should be active immediately.
If the enforcer "lives" across requests, the enforcer.LoadPolicy() should still pull in changes from the database, but it appears db changes are not "honored" by the CasbinAuthorize attribute. We are not sure if the policies are in fact re-read from the database, and the .Enforce() decision has been cached, or if the policies themselves are cached, or if there is something else entirely going on.
Any help and insights are greatly appreciated.
I have an application that uses imperative access control. In this application I cannot use attributes to enforce access to a controller action because the subject, object, and action needed to query the enforcer depend upon conditions that aren't available until much later.
Do you think this package already supports imperative authorization checks, e.g. using custom request transformers, or does it need an extra layer of code that's not there yet?
We wish to provide the HttpRequest object to the RequestTransformer. This will allow the transformer to work out the obj (=request path), and the act method (e.g. GET|POST), without having to explicitly provide those in the CasbinAuthorize attribute. It will also enable scenarios where e.g. the domain/tenant is to be found either in the request headers or in the request content.
I have created a proof of concept which seem to work. So I'm wondering if you are accepting PRs? Or if there are any suitable extension points for this, or if we will be required to fork the project?
I am trying to retrieve objects from our db, based on ids passed by the request, to the enforcer, so that these objects are passed to a custom function when evaluating a policy.
I have created a CustomRequestTransformer (base class BasicRequestTransformer).
Two of the request values I retrieve within this transformer are the oid of the user and a reference id of a tenant. With these ids I want to be able to get the User and Customer object in our database. So that I can return these objects in the requestValues-object of TransfromAsync and so pass them on to the enforcer in DefaultEnforcerService (line 88).
Is there a way to pass the dbcontext with the CustomRequestTransformer through dependency injection when configuring the DefaultRequestTransformer in the services.AddCasbinAuthorization()?
Or is there a way to pass a custom EnforcerService instead of the services.TryAddScoped<IEnforceService, DefaultEnforcerService>(); within AddCasbinAtuhorizationCore().
Or is there another way to enable this?
I did the following:
[CasbinAuthorize("PageTwo", "write")]
public class PageTwoModel : PageModel
{
//....
But no matter what I still get access to the razor page.
Does this not work with Razor Pages?
This commit: cf65b40 has introduced bugs and caused the CI tests to fail: https://github.com/casbin-net/casbin-aspnetcore/actions/runs/4470605463/jobs/7854387801 . This commit has been reverted and backed-up at another branch: https://github.com/casbin-net/casbin-aspnetcore/tree/sagilio
@sagilio next time, please make a PR so we can track whether the code has broken any CI
I'm trying to use Casbin to control access to an api implemented using ApiController. The API uses Jwt bearer tokens.
Will this work with the CasbinAuthorize attribute?
Replacing the standard Authorize(Policy="...) attribute with CasbinAuthorize() does not seem to work. Checking the ClaimsIdentity inside a RequestTransformer shows that the User is not authenticated, and the claims array is empty.
Furthermore I'm redirected to login and gets a 404, instead of the expected 401 error.
So I'm wondering if the CasbinAuthorize attribute is supposed to work for thins kind of use-case?
If not, are there plans to cover use cases with bearer tokens?
I have built and run samples from the sources. received the same issue as already is in the list
Then I have copied the Blazor samples to separate folder, added NuGet package and could not build because of
the options.DefaultRequestTransformerType does not exist :
//Add Casbin Authorization
builder.Services.AddCasbinAuthorization(options =>
{
options.PreferSubClaimType = ClaimTypes.Email;
options.DefaultModelPath = Path.Combine("CasbinConfigs", "basic_model.conf");
options.DefaultPolicyPath = Path.Combine("CasbinConfigs", "basic_policy.csv");
// Comment line below to use the default BasicRequestTransformer
// Note: Commenting the line means that the action methods MUST have [CasbinAuthorize()] attribute which explicitly specifies obj and policy. Otherwise authorization will be denied
options.DefaultRequestTransformerType = typeof(KeyMatchRequestTransformer); // <---- ERROR
});
How to fix it?
Can the aspnet core middleware be configured to use EFCore instead of files to persist policy?
Hello. How can I use query or route params in the CasbinAuthorize? Do I need write a custom transformers for it?
We're looking into using casbin.net to handle authorization in our project. We're looking to protect and authorize access to our backend api's
We're wondering if this project is still under development or if it is abandoned?
I am trying to override the default request transformer for individual controller actions.
Like so:
[CasbinAuthorize(RequestTransformerType = typeof(VerjiCasbinRequestTransformer))]
public async Task<IActionResult> SetPrimaryContact(string customerId, string personId)
{
...
The middleware is not able to pick up the transformer, and fails with:
System.ArgumentException: Can find any specified type request transformer. (Parameter 'RequestTransformerType')
at Casbin.AspNetCore.Authorization.DefaultEnforcerService.EnforceAsync(ICasbinAuthorizationContext context)
at Casbin.AspNetCore.Authorization.Policy.CasbinAuthorizationHandler.HandleRequirementAsync(AuthorizationHandlerContext context, CasbinAuthorizationRequirement requirement, ICasbinAuthorizationContext casbinContext)
at Microsoft.AspNetCore.Authorization.AuthorizationHandler`2.HandleAsync(AuthorizationHandlerContext context)
at Microsoft.AspNetCore.Authorization.DefaultAuthorizationService.AuthorizeAsync(ClaimsPrincipal user, Object resource, IEnumerable`1 requirements)
at Casbin.AspNetCore.Authorization.CasbinEvaluator.AuthorizeAsync(ICasbinAuthorizationContext casbinContext, AuthorizationPolicy policy, AuthenticateResult authenticationResult)
at Casbin.AspNetCore.Authorization.CasbinAuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
at AspNetCoreRateLimit.RateLimitMiddleware`1.Invoke(HttpContext context) in C:\Users\User\Documents\Github\AspNetCoreRateLimit\src\AspNetCoreRateLimit\Middleware\RateLimitMiddleware.cs:line 123
at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)
Not sure how to make CasbinAuthorizeAttribute() use the specific transformer. I've tried creating the transformer in the same namespace as the controller, but with the same result.
Hi guys.
I have this at startup:
public static void AddAclAuthorization(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<CasbinDbContext>(options => options.UseNpgsql(
configuration.GetConnectionString("Casbin"),
options => options.MigrationsHistoryTable("__CasbinMigrationsHistory")
.MigrationsAssembly("MyComp.Casbin")));
services.AddCasbinAuthorization(options =>
{
options.PreferSubClaimType = OpenIDStandardClaims.PreferredUsername;
options.DefaultModelPath = Path.Combine("Authorization", "Models", configuration["Authorization:Casbin:ModelName"]);
options.DefaultEnforcerFactory = (p, m) =>
new Enforcer(m, new EFCoreAdapter(p.GetRequiredService<CasbinDbContext>()));
});
}
And looking for a way to retrieve all available business objects for current user in a ApiController. For doing this I assume to call NetCasbin.Enforcer.GetPermissionsForUser() in my controller, filter 'this and that' and return result to requestor.
Actually I didn't find AddCasbinAuthorization() method in the repo and now looking for a way to get Enforcer or something else to make that call and adding DI to ApiController constructor:
public MyController(ILogger<MyController> logger, DbCtx ctx, IConfiguration configuration, IEnforcer enforcer) // what to inject here?
{
_logger = logger;
_dbContext = ctx;
Configuration = configuration;
Enforcer = enforcer;
}
I'm new to Casbin and not sure what to inject?
It is a custom middleware for the casbin. You can use it
and official authorization together.
I have downloaded WebApplicationWithEfcoreSample sample app, and when i'm trying to run it, recieving such error -
and slightly changed sample .csproj file, modified/added - <PackageReference Include="Casbin.AspNetCore" Version="1.1.0" /> <PackageReference Include="Casbin.NET.Adapter.EFCore" Version="2.1.0" />
When adding the freshest packages for Casbin.Net and Casbin.AspNetCore I get assembly load errors.
I think it may be because the latest released Casbin.Net is v1.5.1 while Casbin.AspNetCore expects v1.5.0
Should the package version in Casbin.AspNetCore perhaps be updated to Casbin.Net v1.5.1 ?
As it stands now, the only implementation of IEnforcerProvider
inside this package, i.e. DefaultEnforcerProvider
, does not integrate with Casbin EFCore Adapter.
Would you consider adding a ICasbinAuthorizationPolicyProvider
compatible with the EFCore Adapter?
Hi.
I saw some questions: #17 , #34 , #36 , #37 , #41 .
Also I saw example https://github.com/casbin-net/casbin-aspnetcore/tree/preview/samples/WebApplicationWithEfcoreSample (thank you for it).
But if I understand all correct, now a default provider not use filters. As I saw in source code a default behaviour for adapters are to load all policies on initialization. But not for optimization the EF core adapter has a lazy loading (when we load zero policies on initialization). Will I need to implement a custom provider for this variant if I want to load policies with a filter before call enforce?
I cloned and ran the sample. after some experiments, I found that if in basic_policy.csv, GET
works but Get
not work.
GET
or POST
, etc. could you please explain a little why in policy.csv the action syntax must be all upper case? Is it related to some http specification? Is it implement dependent(is the behaviour related to operation system/browser versions)?Make the official authorization middleware to support to handle the casbin authorization.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.