Giter Club home page Giter Club logo

casbin-aspnetcore's People

Contributors

asakusarinne avatar dacongda avatar hsluoyz avatar sagilio avatar tanyuu avatar thoraj avatar wlclass avatar zhenglin-li avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

casbin-aspnetcore's Issues

Unable to get overrides for DefaultRequestTransformer and DefaultEnforcerFactory to work

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)

Typo in sample basic_policy.csv: Get or GET?

I cloned and ran the sample. After some experiments, I found that in basic_policy.csv, GET works but Get not work.

  1. I searched and found this issue Case Insensitive Policy Enforcement, and it means casbin is case sensitive. so i assue this sample has a minor typo.
  2. I searched the entire library code, didn't find any hardcoded action string of 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)?

Providing basic Casbin.NET integration and permission authorize DI extension Seperately.

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.

how to use EFCore-Adapter together with casbin-aspnetcore

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?

Enforcer lifecycle, caching etc.

What is the intended lifecycle for enforcer? And how can we ensure enforcer use "fresh data" when:

  • We have a process which use casbin middleware to protect the API endpoints.
  • We have another process which based on events in the system change casbin policies.

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:

  1. What should be the lifecycle scope for CasbinContext?
  2. What is the lifecycle scope of Enforcer if we use the DefaultEnforcerFactory

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.

Support for imperative authorization checks

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?

Make HttpRequest available to RequestTransformer via the CasbinAuthorizationContext or CasbinAuthorizationData

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?

How to pass a custom EnforcerService or how to make dbcontext available to RequestTransformer

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?

Does [CasbinAuthorize] work in Razor Pages?

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?

Use CasbinAuthorize attribute on ApiController

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?

The options.DefaultRequestTransformerType was not found

I have built and run samples from the sources. received the same issue as already is in the list

#55

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?

EFCore persistence

Can the aspnet core middleware be configured to use EFCore instead of files to persist policy?

Is this project abandoned?

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?

How can I make CasbinAuthorize work with a specific request transformer

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.

[Question] How to retrieve NetCasbin.Enforcer from ApiController?

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?

Ef core example - WebApplicationWithEfcoreSample

I have downloaded WebApplicationWithEfcoreSample sample app, and when i'm trying to run it, recieving such error -
vpn_conf_general
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" />

Casbin.Net assembly version

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 ?

Best way to use EF core adapter with filter

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?

Typo in sample policy file? Get should be GET?

I cloned and ran the sample. after some experiments, I found that if in basic_policy.csv, GET works but Get not work.

  1. I searched and found this issue Case Insensitive Policy Enforcement, and it means casbin is case sensitive. so i assue this sample has a minor typo.
  2. I searched the entire library code, didn't find anywhere to specify the action of 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)?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.