Giter Site home page Giter Site logo

casbin / casbin.net Goto Github PK

View Code? Open in Web Editor NEW
1.1K 26.0 105.0 1002 KB

An authorization library that supports access control models like ACL, RBAC, ABAC in .NET (C#)

Home Page: https://casbin.org

License: Apache License 2.0

C# 100.00%
casbin access-control authorization rbac abac acl auth permission dotnet authz

casbin.net's Introduction

Casbin.NET

Build Status Coverage Status Nuget Release Nuget Discord

News: still worry about how to write the correct Casbin policy? Casbin online editor is coming to help! Try it at: http://casbin.org/editor/

Casbin.NET is a powerful and efficient open-source access control library for .NET (C#) projects. It provides support for enforcing authorization based on various access control models.

All the languages supported by Casbin:

golang java nodejs php
Casbin jCasbin node-Casbin PHP-Casbin
production-ready production-ready production-ready production-ready
python dotnet delphi rust
PyCasbin Casbin.NET Casbin4D Casbin-RS
production-ready production-ready experimental production-ready

Table of contents

Supported models

  1. ACL (Access Control List)
  2. ACL with superuser
  3. ACL without users: especially useful for systems that don't have authentication or user log-ins.
  4. ACL without resources: some scenarios may target for a type of resources instead of an individual resource by using permissions like write-article, read-log. It doesn't control the access to a specific article or log.
  5. RBAC (Role-Based Access Control)
  6. RBAC with resource roles: both users and resources can have roles (or groups) at the same time.
  7. RBAC with domains/tenants: users can have different role sets for different domains/tenants.
  8. ABAC (Attribute-Based Access Control): syntax sugar like resource.Owner can be used to get the attribute for a resource.
  9. RESTful: supports paths like /res/*, /res/:id and HTTP methods like GET, POST, PUT, DELETE.
  10. Deny-override: both allow and deny authorizations are supported, deny overrides the allow.
  11. Priority: the policy rules can be prioritized like firewall rules.

How it works?

In Casbin, an access control model is abstracted into a CONF file based on the PERM metamodel (Policy, Effect, Request, Matchers). So switching or upgrading the authorization mechanism for a project is just as simple as modifying a configuration. You can customize your own access control model by combining the available models. For example, you can get RBAC roles and ABAC attributes together inside one model and share one set of policy rules.

The most basic and simplest model in Casbin is ACL. ACL's model CONF is:

# Request definition
[request_definition]
r = sub, obj, act

# Policy definition
[policy_definition]
p = sub, obj, act

# Policy effect
[policy_effect]
e = some(where (p.eft == allow))

# Matchers
[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act

An example policy for ACL model is like:

p, alice, data1, read
p, bob, data2, write

It means:

  • alice can read data1
  • bob can write data2

We also support multi-line mode by appending '\' in the end:

# Matchers
[matchers]
m = r.sub == p.sub && r.obj == p.obj \
  && r.act == p.act

Further more, if you are using ABAC, you can try operator in like following in Casbin golang edition (jCasbin and Node-Casbin are not supported yet):

# Matchers
[matchers]
m = r.obj == p.obj && r.act == p.act || r.obj in ('data2', 'data3')

But you SHOULD make sure that the length of the array is MORE than 1, otherwise there will cause it to panic.

For more operators, you may take a look at govaluate

Features

What Casbin does:

  1. enforce the policy in the classic {subject, object, action} form or a customized form as you defined, both allow and deny authorizations are supported.
  2. handle the storage of the access control model and its policy.
  3. manage the role-user mappings and role-role mappings (aka role hierarchy in RBAC).
  4. support built-in superuser like root or administrator. A superuser can do anything without explict permissions.
  5. multiple built-in operators to support the rule matching. For example, keyMatch can map a resource key /foo/bar to the pattern /foo*.

What Casbin does NOT do:

  1. authentication (aka verify username and password when a user logs in)
  2. manage the list of users or roles. I believe it's more convenient for the project itself to manage these entities. Users usually have their passwords, and Casbin is not designed as a password container. However, Casbin stores the user-role mapping for the RBAC scenario.

Installation

dotnet add package Casbin.NET

Documentation

https://casbin.org/docs/overview

Online editor

You can also use the online editor (http://casbin.org/editor/) to write your Casbin model and policy in your web browser. It provides functionality such as syntax highlighting and code completion, just like an IDE for a programming language.

Tutorials

https://casbin.org/docs/tutorials

Get started

  1. New a Casbin enforcer with a model file and a policy file:

    var e = new Enforcer("path/to/model.conf", "path/to/policy.csv")

Note: you can also initialize an enforcer with policy in DB instead of file, see Persistence section for details.

  1. Add an enforcement hook into your code right before the access happens:

    var sub = "alice" // the user that wants to access a resource.
    var obj = "data1" // the resource that is going to be accessed.
    var act = "read" // the operation that the user performs on the resource.
    
    if (e.Enforce(sub, obj, act)) {
        // permit alice to read data1
    } else {
        // deny the request, show an error
    }
  2. Besides the static policy file, Casbin also provides API for permission management at run-time. For example, You can get all the roles assigned to a user as below:

    var roles = e.GetRolesForUser("alice")

See Policy management APIs for more usage.

  1. Please refer to the Casbin.UnitTest project for more usage.

Policy management

Casbin provides two sets of APIs to manage permissions:

  • Management API: the primitive API that provides full support for Casbin policy management. See here for examples.
  • RBAC API: a more friendly API for RBAC. This API is a subset of Management API. The RBAC users could use this API to simplify the code. See here for examples.

We also provide a web-based UI for model management and policy management:

model editor

policy editor

Policy persistence

https://casbin.org/docs/adapters

Policy consistence between multiple nodes

https://casbin.org/docs/watchers

Role manager

https://casbin.org/docs/role-managers

Benchmarks

https://casbin.org/docs/benchmark

Examples

Model Model file Policy file
ACL basic_model.conf basic_policy.csv
ACL with superuser basic_model_with_root.conf basic_policy.csv
ACL without users basic_model_without_users.conf basic_policy_without_users.csv
ACL without resources basic_model_without_resources.conf basic_policy_without_resources.csv
RBAC rbac_model.conf rbac_policy.csv
RBAC with resource roles rbac_model_with_resource_roles.conf rbac_policy_with_resource_roles.csv
RBAC with domains/tenants rbac_model_with_domains.conf rbac_policy_with_domains.csv
ABAC abac_model.conf N/A
RESTful keymatch_model.conf keymatch_policy.csv
Deny-override rbac_model_with_deny.conf rbac_policy_with_deny.csv
Priority priority_model.conf priority_policy.csv

Middlewares

Authz middlewares for web frameworks: https://casbin.org/docs/middlewares

Our adopters

https://casbin.org/docs/adopters

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! ๐Ÿ™ [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

This project is licensed under the Apache 2.0 license.

casbin.net's People

Contributors

asakusarinne avatar changethecode avatar dacongda avatar dviry avatar gopherj avatar hsluoyz avatar huazhikui avatar janpieterz avatar kyle-mccarthy avatar r4wand avatar sagilio avatar sagilio0728 avatar sbou avatar selflocking avatar sociometry avatar tanyuu avatar zredinger-ccc 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

casbin.net's Issues

Should we need to avoid repeated checking policy exists when call AddPolicy

When we add policy by Enforcer, It will call the AddPolicy method like this:

protected bool AddPolicy(string sec, string ptype, List<string> rule)
{
    if (model.HasPolicy(sec, ptype, rule))
    {
        return false;
    }
    ...
    var ruleAdded = model.AddPolicy(sec, ptype, rule);
    return ruleAdded;
}

But when calling model.AddPolicy it will check again the policy exists like this:

public bool AddPolicy(string sec, string ptype, List<string> rule)
{
    if (!HasPolicy(sec, ptype, rule))
    {
        Model[sec][ptype].Policy.Add(rule);
        return true;
    }
    return false;
}

I think we should avoid repeated checking. but the AddPolicy method in Policy class is a public method. If we modify the existing implementation, It will cause unsafe calling. We can create an internal method without check to avoid it.

Helper.LoadPolicyLine causes poor performance

I'm loading nearly 10000 policies in my project .
the Casbin core module and Adapter is injected as Scoped service.
I found this method checking policy uniqueness every time when data line loaded. I wrote a method

private void PolicyUniquenization(Model model)
        {
            var m = model.Model;
            foreach(var key in m.Keys)
            {
                foreach (var ast in m[key].Values)
                {
                    ast.Policy = ast.Policy.Distinct().ToList();
                }
            }
        }

then alter Helper.LoadPolicyLine method without checking data uniqueness.
and invoke at the end of LoadPolicy method in Adapter

public void LoadPolicy(Model.Model model)
        {
            // some codes of polices loading...

            PolicyUniquenization(model);
        }

seems to make things better?
want to know if this modification causes any problem..

Use semantic-release to automatically release Casbin.NET versions

We already used semantic-release in Go and Nodejs, see Node-Casbin: casbin/node-casbin#153 (comment)

image

There's also a student working on Java: casbin/jcasbin#76

I think we should also integrate it into .NET. It will auto-release to GitHub Releases and Nuget. We need to find a plugin to use semantic-release in .NET project. I found these but not tried any one yet, maybe useful for you:

Can anyone work on it?

support .net framwork?

I'm using .net4.5 and trying to install it via nuget. The lowest version is 1.1.0. and it says requires .net standard2.0.

The question is why doesn't is support .net 4.5(.netstandard1.0)? As far as I know many dotnet core libraries also support .net framework.

The PolicyStringSet property at Assertion.cs do not need to be public

the assertion.PolicyStringSet property does not need to be public.

  1. add assertion.AddPolicy(rule) method in Assertion Class replace these 2 steps:
assertion.Policy.Add(rule);
assertion.PolicyStringSet.Add(Utility.ArrayToString(rule));
  1. add assertion.Contains(rule) mehod in Assertion Class replace Model[sec][ptype].PolicyStringSet.Contains(Utility.ArrayToString(rule))

  2. add assertion.RemovePolicyAt(i) method replace these 2 steps:

assertion.Policy.RemoveAt(i);
assertion.PolicyStringSet.Remove(Utility.ArrayToString(rule));

Originally posted by @huazhikui in #39

IP match can not pass all test cases

string key1 = "192.168.2.123"; string key2 = "192.168.2.0/16";
bool result = BuiltInFunctions.IpMatch(key1, key2);

the result should be true but now is false.

How to enforce a hierarchy for parent/child relationships?

We have a structure like this:

Grand Parent
Parent
Children
Grand Children
So on....

I have two questions:

  1. If user has permission on Parent, how do we find out the grand parent to show as View?
  2. If the user navigates to Grand Children directly for that specific parent, how do we perform that check, and allow access?

Thanks,
Harsimrat

Change the way of integrating RBAC API and Management API to a one Enforcer

I think the best way to integrate IEnforcer (rbac api) and ManagementEnforcer (management api) to a one IEnforcer is use Extension Method to implement it. Here are some reasons:

  1. IEnforcer can be a simple and clean interface.
  2. We can maintain the RBAC and Management API at different class, and we can easy to add new helper type API.
  3. Follow the CARP desgin.

It will become a break change, we should change the protect field to Read-only property (also GetModel method can do it) and delete the InternalEnforcer, ManagementEnforcer and CoreEnforcer and convert them to a Enforcer class which only includes the API in InternalEnforcer and CoreEnforcer in now version).

Relate comment:
#55 (comment)

Change the workflow of creating a model

I think we should move the NewModel API to Model class. It will follow the go implement.
It will be some break changes if we directly delete them, So we can set Obsolete at on them now and remove at the next mainline version.

ABAC with RBAC

Hello
Plaese I want to make access control model with ABAC and only role from RBAC.
its will be only in C#.
the idea is to test this model software in openstack .
( access control model in C# and its will test this kind of access control Policy in openstack if we move to openstack as SaaS)
Please any one could help me.

Thanks

Version 1.2.2.and 1.2.3 dependency issue

I am evaluating Casbin.NET for my company. I have a visual studio 2019 ASP.NET core in .NET framework 4.7.2 project that i am attempting to use the Casbin.NET nuget package with. Version 1.2.0 installs and executes perfectly but 1.22 and 1.23 , though they install, result in an error when an Enforcer is instantiated. The error is "Could not load file or assembly 'DynamicExpresso.Core, Version=2.3.1.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)".

Make assertion properties to read-only for public

The key/value/tokens properties can be set internal write, I think the user should not change them without the model's APIs, and we can implement an IReadOnlyAssertion interface for the assertion that only read the properties. This change will be included in #124.

Parity with main?

I noticed the main project had some recent updates, but not this one. How long does it usually take to catch up?

Contributions are welcome

Currently, we have some unofficial implementations for C#. And maybe it's time to have an official one. I'm not sure if this code base is the best one, but suggestions are always welcome.

@xgenvn, can you help contribute to it?

@huazhikui, can you provide a to-do list?

No rollback of memory data when adapter throw exception

In InternalEnforcer.cs, there are 3 methods add or remove policy data. All these methods will add or delete data in memory first then call adapter to perform the mutation of data in data store behind the adapter.

It will cause data inconsistency issue if no revert or rollback logic in all those methods. Please refers to the bold area of the partial code below:

bool ruleAdded = model.AddPolicy(sec, ptype, rule);
if (!ruleAdded)
{
    return false;
}

if (adapter != null && autoSave)
{
    try
    {
        await adapter.AddPolicyAsync(sec, ptype, rule);
    }
    catch (NotImplementedException)
    {
    }
    catch (Exception e)
    {
       **// rollback logic to revert the related memory data**
        throw e;
    }

    if (watcher != null)
    {
        // error intentionally ignored
        watcher.Update();
    }
}

SavePolicy fails unless model contains [role_definition]

SavePolicy() method fails when trying to save basic_model.conf in the examples folder.

It works if you add this notionally.

[role_definition]
g = _, _

If roles are optional in the model, can we make sure SavePolicy() ignores missing g?

PlatformTarget - x64

Hi,

Why is PlatformTarget set to x64 ?
In my project-configuration I have set this to "Any CPU". I then get a build-warning:

Warning MSB3270 There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "C:\Users\nomha4.nuget\packages\casbin.net\1.2.4\lib\netstandard2.0\NetCasbin.dll", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.

Will it not build on other platforms ?

Fix the code warnings when building

Can we fix the following warnings?

  InternalEnforcer.cs(32, 48): [CS0168] The variable 'e' is declared but never used
  InternalEnforcer.cs(71, 48): [CS0168] The variable 'e' is declared but never used
  InternalEnforcer.cs(109, 48): [CS0168] The variable 'e' is declared but never used
  Config.cs(99, 36): [CS0168] The variable 'e' is declared but never used
  DefaultFileAdapter.cs(29, 32): [CS0168] The variable 'e' is declared but never used
  InternalEnforcer.cs(32, 48): [CS0168] The variable 'e' is declared but never used
  InternalEnforcer.cs(71, 48): [CS0168] The variable 'e' is declared but never used
  DefaultFileAdapter.cs(29, 32): [CS0168] The variable 'e' is declared but never used
  InternalEnforcer.cs(109, 48): [CS0168] The variable 'e' is declared but never used
  Config.cs(99, 36): [CS0168] The variable 'e' is declared but never used
  NuGet.Build.Tasks.Pack.targets(198, 5): [NU5125] The 'licenseUrl' element will be deprecated. Consider using the 'license' element instead.
  NuGet.Build.Tasks.Pack.targets(198, 5): [NU5048] The 'PackageIconUrl'/'iconUrl' element is deprecated. Consider using the 'PackageIcon'/'icon' element instead. Learn more at https://aka.ms/deprecateIconUrl

image

Remove Appveyor CI support

We only need it to provide to the unit test coverage, We can try to use the new version coveralls.net to provide the unit test coverage at Azure Pipeline and it will only depend on .NET Core 3.1 platform.

Develop Casbin.AspNetCore to help use Casbin in ASP NET Core

.ASP NET Core is a free cross-platform open-source and the most popular framework for building web apps and services with .NET and C# now. We need to provide fine support to it.

Description about the Casbin.AspNetCore

It is an extension package for anyone to can use Casbin in ASP NET Core easily.
It will extend from the Microsoft.AspNetCore.Authorization. So It can be compatible with the existing authorization config. And it is also the first step of casbin-sam.

I think we can create a new repository named 'Casbin.AspNetCore' to develop it.

Related issue:

#24

Signing the assembly

It seems the assembly distributed with the nuget package is not signed, this makes it not very handy to reference Casbin.Net from a signed assembly.

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.